通过interface关键字来声明接口。
interface LabelValue {label: string;}// 指定参数的类型是接口类型function print(labelObj:LabelValue){console.log(labelObj.label);}let obj = {label: 'hello',};print(obj); // hello
类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。
可选属性
interface People {name: string;age: number;}function print(people: People){console.log(people.name);console.log(people.age);}let p = {name: 'Tom',age: 30};print(p); // 'Tom' 30
目前是没有问题的,但是如果不传入name或者是age是报错的。需要通过?来解决。
interface People {name?: string;age?: number;}function print(people: People){console.log(people.name);console.log(people.age);}let p = {};print(p); // undefine undefine
只读属性
interface Point {readonly x: number;readonly y: number;}let p1: Point = { x: 10, y: 20 };p1.x = 5; // error!
函数类型
interface Search {(source: string, subString: string): boolean;}let mySearch:Search;mySearch = function(source:string, subString: string) {let result = source.search(subString);return result > -1;}
实际上类型检查只针对数据类型,不针对参数名称,所以可以修改参数名称的 src, sub 这样也是允许的。但是个人不推荐,怕搞混了。
数组类型
interface StringArray {[index: number]: string}let myArr:StringArray;myArr=["str1", "str2"];console.log(myArr[1]); // str1
实现接口
interface ClockInterface {currentTime: Date;setTime(d: Date);}class Clock implements ClockInterface {currentTime:Date;constructor(h: number, m: number){}setTime(d: Date) {this.currentTime = d;}}
接口继承
interface Shape {color: string;}interface Square extends Shape {size: number;}const s = <Square>{};s.color = "blue";s.size = 6000;
接口多继承
interface Shape {color: string;}interface Stroke {width: number;}interface Square extends Shape, Stroke {size: number;}const s = <Square>{};s.color = "blue";s.size = 6000;s.width = 4000;
混合类型
interface Counter {interval: number;reset():void;(start: number): string;}let c: Counter;c(10);c.reset();
