duck typing / structural subtyping, focus on the shape that values have

  1. interface LabelledValue {
  2. label: string;
  3. }
  4. function printLabel(labelledObj: LabelledValue) {
  5. console.log(labelledObj.label);
  6. }
  7. let myObj = {size: 10, label: "Size 10 Object"};
  8. printLabel(myObj);

Optional Properties

  1. interface SquareConfig {
  2. // 加个问号
  3. color?: string;
  4. width: number;
  5. }

Readonly Properties

  1. interface Point {
  2. readonly x: number;
  3. readonly y: number;
  4. }

ReadonlyArray

the same as Array with all mutating methods removed

  1. let a: number[] = [1, 2, 3, 4];
  2. let ro: ReadonlyArray<number> = a;
  3. ro[0] = 12; // error!
  4. ro.push(5); // error!
  5. ro.length = 100; // error!
  6. // error! 因为 a 的类型有 mutating methods, 而 ro 的类型没有
  7. // 可以使用 type assertion 来避免报错, a = ro as number[]
  8. a = ro;

readonly vs const

variable 用 const
property 用 readonly

Express Property Checks

只有可选属性的话还是不够的, 下面这中情况就比较麻烦:

  1. interface SquareConfig {
  2. color?: string;
  3. width?: number;
  4. }
  5. function createSquare(config: SquareConfig): { color: string; area: number } {
  6. // ....
  7. }
  8. // error, 注意, colour, color
  9. let mySquare = createSquare({ colour: 'red', width: 100 });

一般有三种方式这个问题:

  1. 使用 type assertion
  1. let mySquare = createSquare({ colour: 'red', width: 100 } as SquareConfig);
  1. index signature, 更推荐使用这种方式, 详情看下面的 indexable types
  1. // SquareConfig can have any number of properties,
  2. // and as long as they aren’t color or width, their types don’t matter.
  3. interface SquareConfig {
  4. color?: string;
  5. width?: number;
  6. [propName: string]: any;
  7. }
  1. 先将这个 config 对象赋值给一个变量, 最好不要滥用这种方式
  1. // 这样声明 squareOptions, ts 是不会对 squareOptions 进行类型检查的
  2. // 从而以一种看起来很怪异的方式让 createSquare(squareOptions) 摆脱了类型检查
  3. let squareOptions = { colour: "red", width: 100 };
  4. let mySquare = createSquare(squareOptions);

Function Types

interface 除了可以用来描述 object 之外, 还可以用来描述 function
用一种叫 call signature 的格式来描述 function, 长得很像函数声明:

  1. // 定义
  2. interface SearchFunc {
  3. (source: string, subString: string): boolean;
  4. }
  5. // 使用
  6. let mySearch: SearchFunc;
  7. mySearch = function(source: string, subString: string) {
  8. let result = source.search(subString);
  9. return result > -1;
  10. }
  11. // 形参的名字可以随便取, 不必和 interface 一样
  12. let mySearch: SearchFunc;
  13. mySearch = function(src: string, sub: string): boolean {
  14. let result = src.search(sub);
  15. return result > -1;
  16. }
  17. // 因为已经为变量 mySearch 使用了 searchFunc 接口
  18. // 所以 ts 会自动推导参数和返回值的类型, 不用你个个都标清楚
  19. let mySearch: SearchFunc;
  20. mySearch = function(src, sub) {
  21. let result = src.search(sub);
  22. return result > -1;
  23. }

Indexable Types

a[10] , ageMap['daniel'] 这种可以用下标语法访问的对象, 抽象出的类型叫 indexable types

Indexable types have an index signature that describes the types we can use to index into the object

  1. interface StringArray {
  2. [index: number]: string;
  3. }
  4. let myArray: StringArray;
  5. myArray = ["Bob", "Fred"];
  6. let myStr: string = myArray[0];

规定 indexable types 的值的类型都相同:

  1. interface NumberDictionary {
  2. [index: string]: number;
  3. length: number; // ok, length is a number
  4. name: string; // error, the type of 'name' is not a subtype of the indexer
  5. }

支持的 index signature 有两种, string 和 number
但是就算写 obj[100] = xxx, js 也会把 100 转换成 string 类型的 ‘100’, 所以一起用的时候要注意

  1. class Animal {
  2. name: string;
  3. }
  4. class Dog extends Animal {
  5. breed: string;
  6. }
  7. // Error: indexing with a numeric string might get you a completely separate type of Animal!
  8. interface NotOkay {
  9. [x: number]: Animal;
  10. [x: string]: Dog;
  11. }

和 readonly 搭配

  1. interface ReadonlyStringArray {
  2. readonly [index: number]: string;
  3. }
  4. let myArray: ReadonlyStringArray = ["Alice", "Bob"];
  5. myArray[2] = "Mallory"; // error!

Class Types

implementing an inteface

  1. interface ClockInterface {
  2. currentTime: Date;
  3. setTime(d: Date);
  4. }
  5. class Clock implements ClockInterface {
  6. currentTime: Date;
  7. setTime(d: Date) {
  8. this.currentTime = d;
  9. }
  10. constructor(h: number, m: number) { }
  11. }

注意, 一般来说, interface 只检查 the pulic side of the class, 不会管 private 的
但也有例外, 看下面的 Interfaces Extending Classes

Difference between the static and instance sides of classes

一个类可以被分为两部分: static side 和 instance side
当一个 class implements 一个 interface的时候, interface 只对 instance side 进行检查
// 之所以为什么要这么设计需要多练习, 多思考

  1. // 定义了一个 construct signature
  2. interface ClockConstructor {
  3. new (hour: number, minute: number);
  4. }
  5. // Type 'Clock' provides no match for the signature 'new (hour: number, minute: number): any'
  6. // interface 只对 instance side 进行检查
  7. // 然而 constructor 属于 static side, 所以它在 instance side 检查不到就抱怨了
  8. class Clock implements ClockConstructor {
  9. currentTime: Date;
  10. constructor(h: number, m: number) { }
  11. }
  12. // 变通一下
  13. interface ClockConstructor {
  14. new (hour: number, minute: number): ClockInterface;
  15. }
  16. interface ClockInterface {
  17. tick();
  18. }
  19. function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
  20. return new ctor(hour, minute);
  21. }
  22. class DigitalClock implements ClockInterface {
  23. constructor(h: number, m: number) { }
  24. tick() {
  25. console.log("beep beep");
  26. }
  27. }
  28. class AnalogClock implements ClockInterface {
  29. constructor(h: number, m: number) { }
  30. tick() {
  31. console.log("tick tock");
  32. }
  33. }
  34. let digital = createClock(DigitalClock, 12, 17);
  35. let analog = createClock(AnalogClock, 7, 32);

Extending Interfaces

就像 class 可以 extends class 一样, interface 也可以 extends interface
都是为了复用

  1. interface Shape {
  2. color: string;
  3. }
  4. interface Square extends Shape {
  5. sideLength: number;
  6. }
  7. let square = <Square>{};
  8. square.color = "blue";
  9. square.sideLength = 10;
  10. // 多继承
  11. interface Shape {
  12. color: string;
  13. }
  14. interface PenStroke {
  15. penWidth: number;
  16. }
  17. interface Square extends Shape, PenStroke {
  18. sideLength: number;
  19. }
  20. let square = <Square>{};
  21. square.color = "blue";
  22. square.sideLength = 10;
  23. square.penWidth = 5.0;

Hybrid Types

函数也是一个对象, 在 js 里往函数挂一些属性也很常见
所以 interface 也允许你随意组合

  1. interface Counter {
  2. (start: number): string; // function type
  3. interval: number;
  4. reset(): void;
  5. }
  6. function getCounter(): Counter {
  7. let counter = <Counter>function (start: number) { };
  8. counter.interval = 123;
  9. counter.reset = function () { };
  10. return counter;
  11. }
  12. let c = getCounter();
  13. c(10);
  14. c.reset();
  15. c.interval = 5.0;

Interfaces Extending Classes

没错你眼睛没花 , inteface 也能继承 class

When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. This means that when you create an interface that extends a class with private or protected members, that interface type can only be implemented by that class or a subclass of it.

  1. class Control {
  2. private state: any;
  3. }
  4. interface SelectableControl extends Control {
  5. select(): void;
  6. }
  7. class Button extends Control implements SelectableControl {
  8. select() { }
  9. }
  10. class TextBox extends Control {
  11. select() { }
  12. }
  13. // Error: Property 'state' is missing in type 'Image'.
  14. // 就是只能由 Control 的子类来 implements SelectableControl
  15. class Image implements SelectableControl {
  16. select() { }
  17. }
  18. // 这样也是 ok 的, 记住 interface 只检查 shape
  19. let text: SelectableControl = new TextBox()