美文网首页我爱编程
Interfaces of TypeScript

Interfaces of TypeScript

作者: KimYYX | 来源:发表于2018-03-12 10:17 被阅读0次

类型检测(type-checking)是 TypeScript 核心功能之一,而 Interfaces 算是这个核心功能的基石了。

Interfaces 接口,用来定义对象的类型结构。有了结构就能决定其类型(type),然后就可以做校验(checking)。


一、基本使用方法

// color 是字符类型,选填
// width 是数字类型,必填
// shape 是字符类型,必填,且只读(之后不可修改)
// 最后一行表明,该接口还可添加任意数量类型为字符的键值
interface SquareConfig {
    color?: string;
    width: number;
    readonly shape: string;
    [propName: string]: any;
}

二、进阶使用方法

// 定义方法接口
interface SearchFunc {
    (source: string, subString: string): boolean;
}

// 定义数组接口
interface StringArray {
    [index: number]: string;
}

三、高级使用方法

/**
 * 有继承关系对象的 Interface 定义方法
 */
class Animal {
    name: string;
}
// Dog 是 Animal 的子类
class Dog extends Animal {
    breed: string;
}

// 下面是错误的,Dog 一定是 Animal,而 Animal 不一定是 Dog
interface NotOkay {
    [key: string]: Dog;
    point: Animal;
}

// 下面是对的
interface Okay {
    [key: string]: Animal; // 注意这里和上面定义数组写法的区别,一个是number,一个是string
    point: Dog;
}

// 关于上面的解释:
// 具体的使用方法,大家通过下面的例子感受下,我觉得这里意会比较好
let p = <Okay>{ point: new Dog() } // 正确

let p = <Okay>{ a: new Dog(), point: new Dog() } // 正确

let p = <Okay>{ a: new Animal(), point: new Dog() } // 正确

let p = <Okay>{ a: new Animal(), point: new Animal() } // 错误,point类型为Dog

let p = <Okay>{ a: new Dog() } // 错误,没有实现point

let p = <Okay>{ a: new Animal(), point: new Dog(), c: 'Hello' } // 错误,键的值必须为Animal或其子类

相关文章

网友评论

    本文标题:Interfaces of TypeScript

    本文链接:https://www.haomeiwen.com/subject/paogfftx.html