TypeScript的核心原则之一是对值所具有的结构进行类型检查。接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。
interface testType { name: string; age: number; } function test(obj: testType): void { console.log(obj.name); console.log(obj.age); } test({name:"fred",age:20,height:180}) //fred 20
interface:接口关键字,只要传入的对象满足接口的必要条件,那么它就是被允许的。
可选属性(接口定义中加“?”)
interface testType { name: string; age?: number; }
只读属性(readonly)
interface testType { readonly name: string; readonly age: number; } let test1:testType = {name:"fred",age:20} test1.name = "Bob"; //error
额外的属性检查
interface testType { name?: string; age?: number; } function test(conf: testType): void { } test({ nama: "fred", age: 20 }) //error:'nama' dose not exist in type 'testType'
解决方法:a) 断言
test({ nama: "fred", age: 20 } as testType) //断言
b)字符串索引签名
interface testType { name?: string; age?: number; [propName:string]:any; //字符串索引签名 }
c)中间变量绕过类型检测
let test2 = { nama: "fred", age: 20 }; //中间变量绕过类型检测 test(test2)
接口继承(extends)
interface nameFace { name: string; } interface ageFace { age: number; } interface heightFace extends nameFace, ageFace { height: number; } let person = <heightFace>{}; person.name = "fred"; person.age = 20; person.height = 180;
接口继承类
class Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};