TypeScript的核心就是类型检查,接口就是用于声明类型,给内部或第三方使用者提供类型声明和约束。typescript
// 声明数据类型 interface CustomerInfo { customerCode: string; customerName: string; } // 使用数据类型 function helloCustomer(customerInfo: CustomerInfo) { console.log(`Hello, ${customerInfo.customerName}!`); } helloCustomer({customerCode: '1001', customerName: 'Jee'}); // ok helloCustomer({customerName: 'Jee'}); // error, Property 'customerCode' is missing
这里和面向对象语言相似,用于定义对象接口,声明对象的结构,定义类时能够实现接口,知足这个接口定义的功能。编程
// 接口声明 interface Animal { name: string; } // 接口继承 interface Mammal extends Animal { legNum: number; sound(): string; } // 类实现 class Bull implements Mammal { name: string; legNum: number; constructor(name: string) { this.name = name; this.legNum = 4; } sound() { return 'moo'; } } // 实例 let bull1 = new Bull('bull1'); console.log(bull1.sound()); // moo
有两种方式能够实现可变属性,属性明确时,推荐第一种。不明确时能够用第二种。函数
interface CustomerInfo { customerCode: string; customerName: string; customerAddr?: string; // 可选属性 }
interface CustomerInfo { customerCode: string; customerName: string; customerAddr?: string; // 可选属性 [key: string]: any; // 其余任意名称,任意类型的属性 }
这里说明一下,由于JavaScript对象中,数字索引是会转换成string来取值的。若是一个接口里面,同时有number、string索引属性时,number索引属性的类型,必须时string索引属性的子类型。 也就是,number索引的属性类型,必须能被string索引的属性类型覆盖;用number索引去取值,取到的值也是string索引属性的类型。
interface CustomerInfo { static greeting = 'Hello'; // 静态属性 static readonly standardGreeting = 'Hello'; // 只读静态属性 readonly customerCode: string; // 只读属性 customerName: string; // 普通属性 }
const vs readonly,变量用const,属性用readonly
接口除了能描述对象类型,还能描述函数类型(这个和面向对象语言有点不同,须要理解一下)。学习
interface SearchFunc { (content: string, key: string): boolean; } // 这里参数名能够不同,类型也能够省略 let mySearchFunc: SearchFunc = (c, k) => { return c.search(k) > -1; }
会再写一遍类的学习,一篇接口与类的结合使用。this