接口可以理解成一种规范或者说一种契约,是一种抽象的概念可以用来去约定对象的结构。去使用一个接口就必须要去,遵循这个接口全部的约定。在 TS 当中接口最直观的体现就是可以约定一个对象当中具体应该有哪些成员,而且这些成员的类型又是什么样的。
interface Post {
title: string;
content: string;
}
function printPost (post:Post):void {
console.log(post.title);
console.log(post.content)
}
printPost({
title: 'Hello TypeScript',
content: 'A typescript superset'
})
总结:接口就是用来去约束对象的结构,一个对象去实现一个接口就必须要去拥有这个接口当中所约束的所有成员。
对于接口中约定的成员,还有一些特殊的用法:
-
可选成员:在对象当中某一个成员是可有可无的,这样的话对于约束这个对象的接口来说可以使用可选成员这个特性。
interface Post { title: string; content: string; subtitle?: string; // 等价于 subtitle: string | undefined } -
只读成员:设置只读属性的成员,不可再进行编辑
interface Post { title: sting; content: string; subtitle: string; readyonly summary: sring; } const hello:Post = { title: 'Hello TypeScript'; content: 'A javascript superset'; summary: 'A javascript ...' } hello.summary = 'other' // Cannot assign to 'summary' because it is a read-only property -
动态成员:一般适用于一些具有动态成员的对象,例如程序当中的缓存对象。它在运行过程当中,就会出现一些动态的键值。
interface Cache { [key:string]: string } const cache:Cache = {} cache.foo = 'value1' cache.bar = 'value2'