skip to content

TypeScript
let 和 const 在 TS 类型推导中的区别

通过 letconst 定义的赋予了相同值的变量,其推断出来的类型不一样。

比如同样是 'this is string'(这里表示一个字符串值),通过 let 定义的变量类型是 string,而通过 const 定义的变量类型是 'this is string'(这里表示一个字符串字面量类型)。

{
  let str = 'this is string' // 推导出的类型为 string
  let num = 1 // 推导出的类型为 num
  let bool = true // 推导出的类型为 boolean
}

{
  const str = 'this is string' // 推导出的类型为 this is string
  const num = 1 // 推导出的类型为 1
  const bool = true // 推导出的类型为 true
}