接口
TS的核心原则之一是对值所具有的结构进行类型检测
接口初探
function printLabel(labelledObj: { label: string }) { console.log(labelledObj.label);}let myObj = { size: 10, label: "Size 10 Object" };printLabel(myObj);
可选属性
width?: number
interface SquareConfig { color?: string width?: number}function createSquare(config: SquareConfig): { color: string, area: number } { let newSquare = { color: 'white', area: 100 } if (config.color) { newSquare.color = config.color } if (config.width) { newSquare.area = config.width * config.width } return newSquare}let mySquare = createSquare({ color: 'red' })console.log(mySquare)
只读属性
readonly x: number
interface Point { readonly x: number readonly y: number}let p1: Point = { x: 10, y: 20 }p1.x = 20 // error
readonly vs const
如果是变量那么使用const , 如果是属性那么使用readonly
额外的属性检测
[propName: string]: any
interface Square { color?: string width?: number [propName: string]: any}function createSquare(config: Square): {color: string, area: number} { let mySquare = {color: 'white', area: 100} if (config.color) { mySquare.color = config.color } if (config.width) { mySquare.area = config.width * config.width } return mySquare}createSquare({colur: 'black', width: 20})
函数类型
interface SearchFunc { (source: string, subString: string) : boolean}let mySearch: SearchFuncmySearch = function(src: string, str: string) { let result = src.search(str) return result > -1}
可索引的类型
interface StringArray { [index: number]: string}let myArray: StringArraymyArray = ['Bob', "Fred"]let myStr: string = myArray[0]
类类型
interface ClockInterface { currentTime: Date}class Clock implements ClockInterface { currentTime: Date constructor(h:number, m: number) {}}
继承接口
interface Shape { color: string}interface Square extends Shape { sideLen: number}let square = {} as Squaresquare.color = 'red'square.sideLen = 10
混合类型
interface Counter { (start: number): string interval: number reset(): void}function getCounter(): Counter { let counter = (function (start: number) { }) as Counter counter.interval = 123 counter.reset = function () { } return counter}let c = getCounter()c(10)c.reset()c.interval = 4.9