TS-接口
Posted sonwrain
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TS-接口相关的知识,希望对你有一定的参考价值。
接口
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: SearchFunc mySearch = function(src: string, str: string) let result = src.search(str) return result > -1
可索引的类型
interface StringArray [index: number]: string let myArray: StringArray myArray = [‘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 Square square.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
以上是关于TS-接口的主要内容,如果未能解决你的问题,请参考以下文章
已解决在react+ts中 atnd 用 upload 组件报错Failed to execute ‘readAsArrayBuffer,param 1 is notof type Blob(代码片段