定义接口

  1. interface lable {
  2. label: string;
  3. }
  4. function printLabel(obj: lable) {
  5. console.log(obj);
  6. }
  7. let obj = {
  8. size: 10,
  9. label: 'hello',
  10. };
  11. // 有多余属性,不报错,因为obj已经是字面量声明了
  12. printLabel(obj);
  13. // 类型“{ size: number; label: string; }”的参数不能赋给类型“lable”的参数。
  14. printLabel({
  15. size: 10,
  16. label: 'hello',
  17. });

额外参数检查

  1. interface Square {
  2. color: string;
  3. area: number;
  4. }
  5. function crateSquare(config: SquareConfig): Square {
  6. let newSquare = {
  7. color: 'red',
  8. area: 100,
  9. };
  10. if (config.color) {
  11. newSquare.color = config.color;
  12. }
  13. newSquare.area = config.width * config.width;
  14. return newSquare;
  15. }
  16. // error:对象文字可以只指定已知属性,并且“xxx”不在类型“SquareConfig”中。
  17. crateSquare({
  18. color: '#ccc',
  19. width: 10,
  20. // xxx:false
  21. });

解决方法:

  • 方式一:参数先用一个对象字面量声明一下
    1. const config = {
    2. color: '#ccc',
    3. width: 10,
    4. xxx: false,
    5. };
    6. crateSquare(config);
  • 方式二:修改接口,添加任意属性 [propName:string]:any ```typescript interface SquareConfig { color?: string; width: number; // 任意属性

}

  1. - 方式三:使用类型断言 as
  2. ```typescript
  3. crateSquare({
  4. color: '#ccc',
  5. width: 10,
  6. xxx: false,
  7. } as SquareConfig);
  • 方式 4:修改接口,添加额外的参数定义(推荐)

可选属性

  1. interface Animal {
  2. sex?: string;
  3. }

只读属性

readonly

  1. interface Animal {
  2. readonly sex: string;
  3. age: number;
  4. }
  5. var animal: Animal = {
  6. sex: 'male',
  7. age: 20,
  8. };
  9. // error:只读属性不能修改
  10. // animal.sex = 'famale'

只读数组

  1. var arr: ReadonlyArray<number> = [1, 3, 4];
  2. // arr.push(23) 报错,不能修改

用接口定义函数

  1. interface Search {
  2. // 注意不是=> 是冒号:
  3. (source: string, subStr: string): boolean;
  4. }
  5. const searchStr: Search = function (src, subStr) {
  6. return src.search(subStr) > -1;
  7. };

函数的其他定义方式

  • 方式一
    1. function test(a: string): string {
    2. return a;
    3. }
  • 方式二
    1. type TestFun = (a: string) => string;
    2. const test2: TestFun = function (a) {
    3. return a;
    4. };

索引签名

TypeScript 支持两种索引签名:字符串和数字。 可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 number 来索引时,JavaScript 会将它转换成 string 然后再去索引对象。 也就是说用 100(一个 number)去索引等同于使用’100’(一个 string )去索引,因此两者需要保持一致。

  • 数字索引签名
  1. interface numArr {
  2. [index:number]:string
  3. }
  4. let numberArr:numArr = ['string1','string2']
  • 字符串索引签名,描述为字典模式
    索引签名的名称(如:{ [index: string]: { message: string } } 里的 index )除了可读性外,并没有任何意义。例如:如果有一个用户名,你可以使用 { username: string}: { message: string },这有利于下一个开发者理解你的代码。
  1. interface stringObj {
  2. [age: string]: number;
  3. }
  4. let stringO: stringObj = {
  5. key: 111,
  6. };

只读索引签名

  1. interface ReadOnlyStringDictionary {
  2. readonly [x: string]: number | string;
  3. }
  4. var StrDic: ReadOnlyStringDictionary = {
  5. a: 20,
  6. };
  7. // 类型“ReadOnlyStringDictionary”中的索引签名仅允许读取
  8. // StrDic.a = 30 // 不允许d

类实现接口

  • 实例接口
  1. interface IClock {
  2. time: Date;
  3. setTime(date: string): void;
  4. }
  • 构造器接口:
    不能直接使用类实现,可作为一个参数传入
    1. interface IClockConstructor {
    2. new (year: string, month: string): IClock;
    3. }

    使用构造器接口:

接口继承

  1. interface Shape {
  2. color: string;
  3. }
  4. interface Polygon {
  5. area: string;
  6. fill(color: string): void;
  7. }
  8. // 接口继承
  9. interface Circle extends Shape {
  10. width: number;
  11. }

可同时继承多个接口,用,隔开

  1. interface Square extends Shape, Polygon {
  2. width: number;
  3. }

混合类型接口

因为 JavaScript 其动态灵活的特点,有时你会希望一个对象可以同时具有上面提到的多种类型,比如:一个对象可以同时做为函数和对象使用

  1. interface Counter {
  2. (start: number): string;
  3. inteval: number;
  4. reset(): void;
  5. }
  6. function getCounter(): Counter {
  7. let counter = function (start: number) {
  8. console.log(start);
  9. } as Counter;
  10. counter.inteval = 100;
  11. counter.reset = function () {};
  12. return counter;
  13. }
  14. const c = getCounter();
  15. c(10);
  16. c.reset();

接口继承类

  1. class Animal {
  2. private type: any;
  3. }
  4. // 接口继承类,会继承类的所有属性,包括私有属性
  5. interface IDog extends Animal {
  6. run(): void;
  7. }
  8. class Hashiqi extends Animal implements IDog {
  9. run() {
  10. console.log('run');
  11. }
  12. }
  13. class Jinmao extends Animal {
  14. run() {}
  15. }

实现继承类的接口 IDog,需要实现类 Animal 的属性,但是 Taidi 不是 Animal 的子类,所以实现不了。
需要像类 Hashiqi 一样继承类+实现接口。

  1. // error:类型 "Taidi" 中缺少属性 "type",但类型 "IDog" 中需要该属性
  2. class Taidi implements IDog {
  3. // private type:any 写也报错,不写也报错
  4. run() {}
  5. }