联合

7 阅读1分钟

联合类型(Union,|)是什么

表示“可能是其中之一”。

记一句话: 联合 A | B:A 或 B(“二选一/多选一”)

type Id = string | number

let id: Id
id = 1      // ✅
id = 'abc'  // ✅
id = true   // ❌

特点:

  • 用之前通常要收窄(判断它到底是哪一种):
function printId(id: string | number) {
  if (typeof id === 'string') {
    id.toUpperCase()
  } else {
    id.toFixed(0)
  }
}

解读:typeof

解读:toUpperCase() 字符串里的英文字母:小写变大写

解读:toFixed()把数字按指定的小数位数进行四舍五入并格式化,返回值是 字符串。