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)
View Code

只读属性

  readonly x: number

interface Point {
  readonly x: number
  readonly y: number
}

let p1: Point = { x: 10, y: 20 }
p1.x =  20 // error
View Code

  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',  20})
View Code

函数类型

interface SearchFunc {
  (source: string, subString: string) : boolean
}

let mySearch: SearchFunc
mySearch = function(src: string, str: string) {
  let result = src.search(str)
  return result > -1
}
View Code

可索引的类型

interface StringArray {
  [index: number]: string
}

let myArray: StringArray
myArray = ['Bob', "Fred"]

let myStr: string = myArray[0]
View Code

类类型

interface ClockInterface {
  currentTime: Date
}

class Clock implements ClockInterface {
  currentTime: Date
  constructor(h:number, m: number) {}
}
View Code

继承接口

interface Shape {
  color: string
}

interface Square extends Shape {
  sideLen: number
}

let square = {} as Square
square.color = 'red'
square.sideLen = 10
View Code

混合类型

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
View Code
原文地址:https://www.cnblogs.com/sonwrain/p/11001478.html