简友广场

TypeScript高级类型之交叉类型、联合类型、类型别名

2019-11-28  本文已影响0人  不思量q
// 交叉类型将多个类型合并为一个类型,
// 联合类型,适合属性为多种类型之一的场景,如字符串或者数组
function formatCommandLine(command: string[] | string) {
  let line = ''
  if(typeof command === 'string') {
    line = command.trim()
  } else {
    line = command.join('').trim()
  }
  return line
}
console.log(formatCommandLine(['a', 'b', 'c'])) // abc
console.log(formatCommandLine(' a fa fas')) // a fa fas

// 类型别名
type many = string | boolean | number
const many1: many = 2
const many2: many = '2oops'

type container<T> = { value: T } // 泛型作为类型别名
// 类型在属性中引用自己
type Tree<T> = {
  value: T,
  left: Tree<T>
}
// interface和类型别名的区别,interface只能定义对象,
// 而type可以定义对象,原始类型,交叉类型,联合类型等
// interface可以实现接口的extends和implements,也可以实现接口合并声明
type Alias = { num: number }
interface aliasInterface {
  num: number
}
declare function aliased(arg: Alias): Alias
declare function interfaced(arg: aliasInterface): aliasInterface
上一篇下一篇

猜你喜欢

热点阅读