typescript 记录

45 阅读1分钟

每日一言: 爱因斯坦说:”如果不能用简单的语言解释出来,说明你还没有完全理解透“

丹麦物理学家尼·波尔表示: ”清晰的思维才会有清晰的表达“

1、[value: string]: string的使用


interface BillOrder {
  id: string
  [value: string]: string | Array<string>
}
let orderInfo = ref<BillOrder>({})

上面代码 表示除了id属性必须存在 其它属性可以随便加

2、异步函数返回值类型声明

const getDetail = async (): Promise<void> => {
  const { code, result } = await $ajax({ url: '/services/h1/platformReconcile/reconcileInvoiceDetail', method: 'post', data: { id: 1 } })
  if (code !== 200) return
  orderInfo.value = result
} 

返回值 Promise 取决于resolve(T)

3、 如果提示类型“LocationQueryValue | LocationQueryValue[]”的参数不能赋给类型“string”的参数。 解决办法: 需要用类型断言as

    typeDesc.value = route.query.type as string

注意类型断言并不是真的改变数据的类型,而是假定,是对typescript编译器的一种欺骗,不能保证运行时不会报错 类型断言分为“<>” 和 “as”

4、type 和 interface

相同点
1、都可以描述对象类型
2、都可以实现继承,interface使用extends, type配合交叉类型实现

不同点
1type除了能描述对象还能描述其它自定义类型
2、同名的interface会合并(属性取并集, 不能出现类型冲突)
3、同名type会报错