0
点赞
收藏
分享

微信扫一扫

TypeScript学习笔记(二)

Brose 2022-04-18 阅读 110
javascript

一、接口

通俗来说就是用来约束对象的结构,一个对象要去实现一个接口他就要去拥有接口中所约束的所有成员

interface Data {
  url: string // 可以用逗号(,)、分号(;)(这里的分号同Javascript分号相同可省略)进行分割。
  tit: string
  subTit?: string // 可选属性,等价于subTit: string | undefind
  readonly summary: string // 只读属性,初始化值后不能修改
}

function get (data: Data) {
  console.log(data.url)
  console.log(data.tit)
}

get({
  url: 'http://www.xxx.com',
  tit: 'test'
}) 

// 动态属性

interface Cache {
  [prop: string]: string // 这里的prop不是固定的可以是任意值,只是代表了属性名称
}

const cache: Cache = {}

cache.foo = 'val1'
cache.bar = 'val2'

 编译过后并不会出现在源代码中,只是用于类型约束

举报

相关推荐

0 条评论