属性检查
- 类接口带有几个确定的属性,同时还会带有其他不确定的属性时,可如下定义:
interface SquareConfig {
color?: string
width?: number
[propName: string]: any
}
- 使用类型断言(as)跳过检查
let mySquare = createSquare({ 100, opacity: 0.5 } as SquareConfig)
可索引的类型
interface StringArray {
[index: number]: string
}
let myArray: StringArray
myArray = ['Bob', 'Fred']
let myStr: string = myArray[0]
这个索引签名表示了当用 number 去索引 StringArray 时会得到 string 类型的返回值。
函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
func1(arg1: string, arg2: any): void;
func2(arg1: number, arg2?: boolean): number;
}
类类型
实现接口
接口描述了类的公共部分,而不是公共和私有两部分。
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 ClockConstructor {
new (hour: number, minute: number): ClockInterface
}
interface ClockInterface {
tick()
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute)
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log('beep beep')
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log('tick tock')
}
}
let digital = createClock(DigitalClock, 12, 17)
let analog = createClock(AnalogClock, 7, 32)
createClock 的第一个参数是 ClockConstructor 类型,在 createClock(AnalogClock, 7, 32) 里,会检查 AnalogClock 是否符合构造函数签名。
继承接口
interface Shape {
color: string
}
interface PenStroke {
penWidth: number
}
interface myColor extends Shape {
fontSize: number
}
interface Square extends Shape, PenStroke {
sideLength: number
}
let square = {} as Square
square.color = 'blue'
square.sideLength = 10
square.penWidth = 5.0