接口
2021-12-29 本文已影响0人
DeadMoon
描述: TypeScript 的核心原则之一是对值所具有的结构进行类型检查。 在TypeScript里,接口的作用就是为这些类型定义规则。
语法:
/** interface 关键字 { 规则 } */
ts 中声明类型结构可以通过内联注解,但是这种方式不可以复用,为规范代码还是不推荐这么做
// 内联注解
const chenghao: {name: string, age: number} = {name: 'chenghao', age: 20} // bad
// good
interface Person {
name: string,
age: number
}
const chenghao: Person = {name: 'chenghao', age: 20} // 属性必须和接口一致
- 支持可选属性(?)
当对一个类型结构中的某个属性是非必填的, 我们就可以使用可选属性interface Staff { job?: string, // 可选的 name: string, age: number } const xh: Staff = {name: '小红', age: 20} // success
- 只读属性(readonly)
interface Staff { nickName: string, readonly sex: string } const ch: Staff = { company: 'xx', nickName: '老实人', sex: '男' } ch.sex = '女' // 无法分配到 "sex" ,因为它是只读属性。ts(2540)
- 函数类型
接口能够描述JavaScript中对象拥有的各种各样的外形.除了描述带有属性的普通对象外,接口也可以描述函数类型。interface Log { (arg: string): void } const log: Log = (msg: string) => {console.log(msg)} // ok const log: Log = (msg: number) => { console.log(msg) } // 参数“msg”和“arg” 的类型不兼容。不能将类型“string”分配给类型“number”。ts(2322) }
- 可索引的类型
描述能够“通过索引得到”的类型// 对象 interface Obj { [prop: string]: any } // 数组 interface ArrayString extends {length: number} { [index: number]: string }
- 类类型
明确的强制一个类去符合某种契约interface ClockInterface { currentTime: Date; setTime(d: Date); } class Clock implements ClockInterface { currentTime: Date; setTime(d: Date) { this.currentTime = d; } constructor(h: number, m: number) { } }
- 继承
一个接口可以继承多个接口,创建出多个接口的合成接口interface Person { name: string } interface Job { kind: string } interface Staff extends Person, Job {} const xh: Staff = {name: 'xiaohong', kind: 'coder'}