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. 数据结构《14》----并查集 Union-Find

    描述: 并查集是一种描述解决等价关系.能够方便地描述不相交的多个集合. 支持如下操作    1. 建立包含元素 x 的集合  MakeSet(x) 2. 查找给定元素所在的集合 Find(x), 返回 ...

  2. River Crossing 简单的动态规划 .

    第一行 t  表示有几组测试数据 . 每组测试数据的 第一行是 n, m   .     然后 下面有n行数据  . 题意:有1个人和N只羊要过河.一个人单独过河花费的时间是M,每次带一只羊过河花费时 ...

  3. # 20145210 《Java程序设计》第06周学习总结

    教材学习内容总结 第十章 输入\输出 10.1 InputStream与OutputStream •串流设计的概念 •java将输入\输出抽象化为串流,数据有来源及目的地,衔接两者的是串流对象 •从应 ...

  4. 《JavaScript Ninja》之挥舞函数

    挥舞函数 匿名函数为什么如此重要 通常使用匿名函数的情况是,创建一个供以后使用的函数.例如,将匿名函数保存在一个变量里,将其作为一个对象的方法,或者是将匿名函数作为一个回调.-->在这些情况下, ...

  5. spark mllib k-means算法实现

    package iie.udps.example.spark.mllib; import java.util.regex.Pattern; import org.apache.spark.SparkC ...

  6. [POJ] 3277 .City Horizon(离散+线段树)

    来自这两篇博客的总结 http://blog.csdn.net/SunnyYoona/article/details/43938355 http://m.blog.csdn.net/blog/mr_z ...

  7. UVa 12558 - Egyptian Fractions (HARD version)

    题目大意: 给出一个真分数,把它分解成最少的埃及分数的和.同时给出了k个数,不能作为分母出现,要求解的最小的分数的分母尽量大. 分析: 迭代加深搜索,求埃及分数的基础上,加上禁用限制就可以了.具体可以 ...

  8. iOS学习笔记---C语言第三天

    循环结构 : while循环   do...while循环(几乎不用)     for循环(使用最多) 特点:在给定的条件成立时,反复执行某程序段,直到条件不成立为止. 给定的条件为循环条件,反复执行 ...

  9. python 数据结构之双向链表的实现

    和单链表类似,只不过是增加了一个指向前面一个元素的指针而已. 示意图: python 实现代码: #!/usr/bin/python # -*- coding: utf-8 -*- class Nod ...

  10. ANTLR3完全参考指南读书笔记[04]

    前言 学习框架或第三方库的方法是什么 (1)少量的浏览manual或tutoral,只关注程序所需的特征,再完善其详细内容和特征的认识? (2)花大量的时间研究详细内容,再考虑程序实现? 这是个先有鸡 ...