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)
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-接口的主要内容,如果未能解决你的问题,请参考以下文章

已解决在react+ts中 atnd 用 upload 组件报错Failed to execute ‘readAsArrayBuffer,param 1 is notof type Blob(代码片段

python小白学习记录 多线程爬取ts片段

ts的接口

使用复杂的 .d.ts 文件 (chrome-app.d.ts)

从父片段到选项卡片段的接口侦听器不起作用

TypeScript 接口