Skip to content

字面量类型

字符串字面量类型、数字字面量类型、布尔字面量类型

ts
{
  let specifiedStr: 'this is string' = 'this is string'
  let specifiedNum: 1 = 1
  let specifiedBoolean: true = true
}

字面量联合类型描述了一个明确,可 'up' 可 'down' 的集合

ts
type Direction = 'up' | 'down'

function move(dir: Direction) {
  // ...
}
move('up') // ok
move('right') // ts(2345) Argument of type '"right"' is not assignable to parameter of type 'Direction'

let 和 const 分析

const :类型为字面量类型

ts
{
  const str = 'this is string' // str: 'this is string'
  const num = 1 // num: 1
  const bool = true // bool: true
}

let:类型为字面量类型的父类型

ts
{
  let str = 'this is string' // str: string
  let num = 1 // num: number
  let bool = true // bool: boolean
}