接口
是一种能力,一种约束
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| (()=>{ interface IPerson{ firstName:string, lastName:string }, function showFullName(person:IPerson) { return person.firstName+'_'+person.lastName } const person = { firstName:'东方', lastName:'不败', } console.log(showFullName(person)) })()
|
TypeScript 的核心原则之一是对值所具有的结构进行类型检查。我们使用接口(Interfaces)来定义对象的类型。接口是对象的状态(属性)和行为(方法)的抽象(描述)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
interface IPerson { id: number name: string age: number sex: string }
const person1: IPerson = { id: 1, name: 'tom', age: 20, sex: '男' }
|
可选属性
接口里的属性不全都是必需的。 有些是只在某些条件下存在,或者根本不存在。
带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个 ? 符号。
可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误。
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface IPerson { id: number name: string age: number sex?: string }
const person2: IPerson = { id: 1, name: 'tom', age: 20, }
|
只读属性
一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly 来指定只读属性:
一旦赋值后再也不能被改变了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| interface IPerson { readonly id: number name: string age: number sex?: string } const person2: IPerson = { id: 2, name: 'tom', age: 20, } person2.id = 2
|
函数类型
接口能够描述 JavaScript 中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外,接口也可以描述函数类型。
为了使用接口表示函数类型,我们需要给接口定义一个调用签名。它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。
1 2 3 4 5 6 7
|
interface SearchFunc { (source: string, subString: string): boolean }
|
这样定义后,我们可以像使用其它接口一样使用这个函数类型的接口。 下例展示了如何创建一个函数类型的变量,并将一个同类型的函数赋值给这个变量。
1 2 3 4 5
| const mySearch: SearchFunc = function (source: string, sub: string): boolean { return source.search(sub) > -1 }
console.log(mySearch('abcd', 'bc'))
|
类类型
类实现接口
与 C# 或 Java 里接口的基本作用一样,TypeScript 也能够用它来明确的强制一个类去符合某种契约。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
interface Alarm { alert(): any; }
interface Light { lightOn(): void; lightOff(): void; }
class Car implements Alarm { alert() { console.log('Car alert'); } }
class Car2 implements Alarm, Light { alert() { console.log('Car alert'); } lightOn() { console.log('Car light on'); } lightOff() { console.log('Car light off'); } }
interface LightableAlarm extends Alarm, Light {
}
|
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!