类型断言

有时候你会遇到这样的情况,你会比 TypeScript 更了解某个值的详细信息。 通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。
通过类型断言这种方式可以告诉编译器变量类型。 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript 会假设你已经进行了必须的检查。

类型断言有两种形式。 其一是“尖括号”语法

  1. let someValue: any = 'this is a string'
  2. let strLength: number = (<string>someValue).length

另一个为 as 语法

  1. let someValue: any = 'this is a string'
  2. let strLength: number = (someValue as string).length

两种形式是等价的。 至于使用哪个大多数情况下是凭个人喜好, 然而, 当你在 TypeScript 里使用 JSX 时,只有 as 语法断言是被允许的

变量声明

let vs. const

现在我们有两种作用域相似的声明方式,我们自然会问到底应该使用哪个。与大多数泛泛的问题一样,答案是:依情况而定。
使用最小特权原则,所有变量除了你计划去修改的都应该使用 const。 基本原则就是如果一个变量不需要对它写入,那么其它使用这些代码的人也不能够写入它们,并且要思考为什么会需要对这些变量重新赋值。使用 const 也可以让我们更容易的推测数据的流动。

解构

作用于函数参数

  1. let input: [number, number] = [1, 2]
  2. function f([first, second]: [number, number]) {
  3. console.log(first)
  4. console.log(second)
  5. }
  6. f(input)

属性重命名

  1. let o = {
  2. a: 'foo',
  3. b: 12,
  4. c: 'bar'
  5. }
  6. let { a: newName1, b: newName2 } = o
  7. // 令人困惑的是,这里的冒号不是指示类型的。 如果你想指定它的类型,仍然需要在其后写上完整的模式。
  8. let { a: newA, b: newB }: {a: string | number, b: number} = o

默认值

默认值可以让你在属性为 undefined 时使用缺省值

  1. function getObject(obj: { a: string, b?: number }) {
  2. let { a, b = 1001 } = obj
  3. }
  4. type C = { a: string, b?: number }
  5. function f({ a, b }: C): void {
  6. // ...
  7. }
  8. // 解构
  9. type obj = { a: string, b?: number }
  10. // a, b都有默认值
  11. function f({ a = '', b = 0 } = {}): void {
  12. // ...
  13. }
  14. // a必传 b默认值
  15. function f({ a: newA, b: newB = 0 }: obj = { a: '' }): void {
  16. // ...
  17. console.log(a, newA, b, newB) // 会提示找不到b, 编译后会提示找不到a
  18. }
  19. f({ a: 'yes' }) // OK, 默认 b = 0
  20. f() // OK, 默认 a: '', b = 0
  21. f({}) // Error, 一旦传入参数则 a 是必须的