发布于 4年前

TypeScript:接口(interface)属性的定义

在TypeScript里,接口扮演了一个定义数据结构的角色,它在TypeScript的类型检查中起到很重要的作用。

基本用法

匿名定义

sayHello(person: {name:string}) {
    console.log(person.name + ", 您好!");
}

这是一个很简单的例子,它使用匿名的方式定义了一个只有属性名为name,类型为string的接口。

TypeScript会对传给sayHello的数据做类型检查,只接收包含了name属性的对象。

显式定义

使用关键词interface可以显式定义接口,上面的例子可以改为:

interface Person {
   name: string;
}

sayHello(person: Person) {
  console.log(person.name)
}

定义属性使用冒号(:)分割,冒号前为属性名,冒号后为属性类型。 例子里name为属性名,string为属性类型。

接口的实现与使用

隐式实现

let person = {name:"张三", age: 19}
sayHello(person);  //输出  张三,您好

TypeScript不同于Java等一些语言,接口的实现不需要显式继承于接口,它只要满足了接口定义的属性即可。

这个示例里,person没有显式继承Person接口,因为它包含了属性name,且类型为string,person变量符合Person接口的,所有它会通过TypeScript的类型检查。

显式实现

class使用implements关键词实现接口。

class Student implements Person {
  name: String;
  age: number;
}

属性

接口的属性可以是可选的,也可以是只读。

可选属性

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

function createSquare(config: SquareConfig): {color: string; area: number} {
    let newSquare = {color: "white", area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: "black"});

在属性名后加上问号(?)的属性为可选属性。

接口并非是所有的属性都是必需的,它允许接口里的一些属性不被赋值或接口的实现对象没有此属性。

在使用可选属性时,有些情况需要对属性进行判断,以便检测属性是否存在或是否有值。

只读属性

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

使用关键词readonly来声明只读属性。只读属性,顾名思义,属性是不允许被重新赋值,只允许读取它的值。

let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

注意:这里要区分一下readonly和const的使用,变量使用const,属性使用readonly。

©2020 edoou.com   京ICP备16001874号-3