码迷,mamicode.com
首页 > 其他好文 > 详细

TS-接口

时间:2019-06-11 09:23:11      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:oid   creat   new   yar   source   only   检测   div   size   

接口

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, width: 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

 

TS-接口

标签:oid   creat   new   yar   source   only   检测   div   size   

原文地址:https://www.cnblogs.com/sonwrain/p/11001478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!