Best practices

This is a guide to the best practices to follow when creating typing files. There are a variety of different ways that typing files can be constructed. Different approaches can be used - this is intended as a guide to what approaches make sense in certain scenarios.

Also, it's a steer on how to deal with limitations in TypeScript. As much as it hurts to say it, TypeScript v1.0 is not flawless. There are certain minor flaws / shortcomings in the language which have implicatations for how typings are created. Here we will detail those limitations, how they can be worked around at present and how you can best vote for improvements in the language on the TypeScript site.

Ghost modules

Also called non-instantiated modules. Instead of polluting the global namespace with many interfaces, it is okay to create a module that contains interfaces only. This does not introduce a variable on the global namespace (see safety in below sample) and this module can only be used for types.

// this pattern has 3 name in top level
interface NodeFoo { }
interface NodeBar { }
interface NodeBuzz { } // this ghost module has 1 name in top level
declare module NodeJS {
interface Foo { }
interface Bar { }
interface Buzz { }
} // safety!
var n = NodeJS; // TS Error : Could not find symbol NodeJS

This also allows you to open up further customization in external modules as interfaces declared inside external module declarations cannot be extended e.g. the following is good as people can customize foo further in other library definitions.

// Usage when declaring an external module
declare module 'foo' {
var foo: NodeJS.Foo;
export = foo;
}

Extending built-in types

There isn't a way to add static members to native objects at the moment as lib.d.ts defines them as a var Date:{/*members*/} and vars are not extendable. Two solutions are proposed to the TS team. Either use interfaces instead of var in lib.d.ts (vote) and/or make variables/classes open ended (vote)

For adding members to instances of native types there are relevant interfaces in available in lib.d.ts e.g.

// add members to Date instances
interface Date {
newMember: number;
} // usage
var foo = new Date();
foo.newMember = 123; // okay

Getter / Setter

Instead of :

declare function duration(value?: number): any;

better to do:

declare function duration(): number;
declare function duration(value: number): void;

Fluent

Pretty self explanatory:

interface Something {
foo(): Something;
bar(): Something;
}

Callback signatures

Do not mark callback arguments as optional if they are passed in everytime by the calling code. Also leave the return as any if the calling code doesn't care. For example in the following good declaration foo is the calling code we are declaring that always calls with bar and bas and doesn't care of the callback return value:

declare function foo(callback: (bar: any, bas: any) => any): void;

// Usage is as expected by a JavaScript developer
foo(() => { });
foo((bar) => 123);
foo((bar, bas) => '');

wrong way to model it would be as shown below as it enforces restrictions the original calling code doesn't impose:

declare function foo(callback: (bar?: any, bas?: any) => void);

Function Overloading

A Union Type (any for now) is needed only for config object bags. For functions / constructors use function overloading e.g.

declare class Foo {
constructor(foo: number);
constructor(foo: string);
} new Foo(123); // okay
new Foo('123'); // okay
new Foo(true); // Error

Overload Ordering

Code with overloads must be manually sorted from the tightest/more-specific overload to loosest. See example below:

interface Parent { x; }
interface Child extends Parent { y; } function foo(p: Child): Child;
function foo(p: Parent): Parent;
function foo(p: any): any;
function foo(p: any) { return p; } var a = foo({ x: 3, y: 4 }); // a: Child
var b = foo({ x: 5 }); // b: Parent var y: any;
var c = foo(y); // c: any

The repository for high quality TypeScript type definitions的更多相关文章

  1. [TypeScript] Type Definitions and Modules

    For example you are building your own module, the same as Lodash: my-lodash.d.ts declare module &quo ...

  2. (TODO:)下载图片,报错:warning: could not load any Objective-C class information from the dyld shared cache. This will significantly reduce the quality of type information available.

    想使用NSInvocationOperation下载图片,然而并没有下载下来, NSData为nil, 还有报错:(打断点就报错) warning: could not load any Object ...

  3. Hex-Rays decompiler type definitions and convenience macros

    /****************************************************************************************** Copyrigh ...

  4. [Typescript] Installing Promise Type Definitions Using the lib Built-In Types

    To fix Promise is not recolized in TypeScript, we can choose to use a lib: npm i @types/es6-promise ...

  5. TypeScript Type Innference(类型推断)

    在这一节,我们将介绍TypeScript中的类型推断.我们将会讨论类型推断需要在何处用到以及如何推断. 基础 在TypeScript中,在几个没有明确指定类型注释的地方将会使用类型推断来提供类型信息. ...

  6. TypeScript: type alias 与 interface

    官方文档中有关于两者对比的信息,隐藏在 TypeScript Handbook 中,见 Interfaces vs. Type Aliases 部分. 但因为这一部分很久没更新了,所以其中描述的内容不 ...

  7. [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5

    Typescript 2.5 adds JSDoc type assertion support for javascript file via ts-check service. First of ...

  8. TypeScript Type Compatibility(类型兼容)

    TypeScript中的类型兼容是基于结构归类的.在普通分类的相比之下,结构归类是一种纯粹用于将其成员的类型进行关联的方法.思考下面的代码: interface Named { name: strin ...

  9. TypeScript type 类型别名

    //6,类型别名 /**类型别名不能出现在声明右侧的任何地方. * 接口 vs. 类型别名 * 另一个重要区别是类型别名不能被extends和implements(自己也不能extends和imple ...

随机推荐

  1. 算法----序列和的 top N

    Description: 两个长度为 n 的数组 A 和 B, 各从中选出一个元素相加 A[i] + B[j], 求 top n 小的那些和. 思路 1:这样的和总共有 n^2 个, 排序,然后取前 ...

  2. Net use命令

    以指定账户密码建立网络磁盘 net use s: \\ip\ipc$  "密码" /user:“用户名”

  3. Java课程作业1

    模仿JavaAppArguments.java实例,编写一个程序,此程序从命令行接受多个数字,求和之后输出. 设计思想:命令行参数都是字符串,必须将其转化成数字才能相加,定义一个数组接收字符串转化的数 ...

  4. Android弹出选项框及指示箭头动画选择

     Android弹出选项框及指示箭头动画选择 Android原生的Spinner提供了下拉列表选项框,但在一些流行的APP中,原生的Spinner似乎不太受待见,而通常会有下图所示的下拉列表选项框 ...

  5. 简单的多线程(活用OD解决运行时错误)

    代码源自<VC++深入详解>第15章 “多线程”,位于第563页 - 566 页. 程序的目的是展示多线程运行的效果: #include <windows.h> #includ ...

  6. 1、SQL基础整理(基本查询)

    分离.附加.备份.还原 --去重 select distinct 列名from表名 --更新 update fenshu set name = ‘李四’where code = 9 --更改表名 sp ...

  7. asp.net ToString()格式汇总

    C 货币 2.5.ToString("C") ¥2.50 D 十进制数 25.ToString("D5") 00025 E 科学型 25000.ToString ...

  8. HDU5772 (最小割)

    Problem String problem (HDU5772) 题目大意 给定一个由数字组成的字符串(n<=100),挑选出一些字符组成一个新的字符串. 字符串的价值: sigma w[id( ...

  9. .csproj文件的配置 IIS可以调试

    <ProjectExtensions> <VisualStudio> <FlavorProperties GUID="{349c5851-65df-11da-9 ...

  10. USB协议-USB的包结构及包的分类

    USB是串行总线,所以数据是一位一位地在数据线上传送的.既然是一位一位地传送,就存在着一个数据位先后的问题.USB使用的是LSB在前的方式,即先出来的是最低位数据,接下来是次低位,最后是最高位(MSB ...