interface 定义接口。
检测对象的属性,属性的顺序不检测,只检测属性是否存在,属性类型是否和接口一致。
- interface IPerson {
- name: string;
- age: number;
- }
- function say(person: IPerson): void {
- console.log(`my name is ${person.name}, and age is ${person.age}`);
- }
- let me = {
- name: "funlee",
- age: 18,
- };
- say(me); // my name is funlee, and age is 18
属性后加 ? 符号,表示可选。
- interface IPerson {
- name: string;
- age: number;
- // love 可选
- love?: string;
- }
属性前加 readonly,表示只读。
- interface IPerson {
- // name 只读
- readonly name: string;
- age: number;
- love?: string;
- }
- let me: IPerson = {
- name: "funlee",
- age: 18,
- };
- // name 不允许被赋值
- me.name = "new name"; // error!
定义函数的参数和返回值类型
- interface IGetArea {
- (w: number, h: number): number;
- }
- const getArea: IGetArea = (w, h) => {
- return w * h;
- };
- getArea(10, 20) // 200
一个接口可以继承多个接口,创建出多个接口的合成接口,如:
- interface IName {
- name: string;
- }
- interface IAge {
- age: number;
- }
- interface IPerson extends IName, IAge {
- sex: string;
- }
- const yqcoder: IPerson = {
- name: "yqcoder",
- age: 18,
- sex: "man",
- }; // { name: 'yqcoder', age: 18, sex: 'man' }
让对象同时作为函数和对象使用,并带有额外的属性,如:
- interface IMixDemo {
- (arg: string): void;
- defaultStr: string;
- }
- function demo(): IMixDemo {
- let x = <IMixDemo>function (str: string) {
- console.log(str);
- };
- x.defaultStr = "yqcoder";
- return x;
- }
- const yq = demo(); // { [Function: x] defaultStr: 'yqcoder' }
- yq('你好'); // 你好