TypeScript学习笔记

4手册指南

4.1接口

  • 可选属性

interface SquareConfig { color?: string; width?: number; }

  • 只读属性

interface Point { readonly x: number; readonly y: number; }

ReadonlyArray<T>类型

  • 类型断言

a = ro as number[];

  • readonly vs const

做为变量使用的话用const,若做为属性则使用readonly const变量为对象时,

可以改变对象的值

  • 额外的属性检查

类型断言、添加一个字符串索引签名、定义临时变量可以绕开检查

类型断言:let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

添加一个字符串索引签名:interface SquareConfig { color?: string; width?: number; [propName: string]: any; }

定义临时变量:let squareOptions = { colour: "red", width: 100 }; let mySquare = createSquare(squareOptions);

  • 函数类型

interface SearchFunc { (source: string, subString: string): boolean; }

  • 可索引的类型

interface StringArray { [index: number]: string; }

let myArray: StringArray;

myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

TypeScript支持两种索引签名:字符串和数字

  • 混合类型

interface Counter {

  (start: number): string;

  interval: number;

  reset(): void;

}
function getCounter(): Counter {

  let counter = <Counter>function (start: number) { };

  counter.interval = 123;

  counter.reset = function () { };

  return counter;

}

let c = getCounter();

c(10);

c.reset();

c.interval = 5.0;

  • 接口继承类

class Control {

  private state: any;

}

interface SelectableControl extends Control { select(): void; }

posted on 2020-02-26 00:41  dbolodb  阅读(227)  评论(0编辑  收藏  举报