FumadocsZDecode
Typescript

断言

TypeScript 提供三种断言方式,让你在编译器推断不足时主动告知类型信息:类型断言非空断言断言函数

类型断言(as)

当你比编译器更清楚一个值的类型时,使用 as 将其转换为目标类型。

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

类型断言不会在运行时做任何转换,它只影响编译阶段的类型检查。

非空断言(!)

在一个可能为 nullundefined 的表达式后加 !,告诉 TypeScript 该值在此处一定存在。

function getStringLength(input: string | null | undefined): number {
  return input!.length
}

只有在你确定该值不为空时才使用 !,否则运行时会抛出错误。

断言函数(asserts)

断言函数通过 asserts condition 返回类型,让 TypeScript 在函数通过后收窄调用处的类型。

function assert(condition: unknown, msg?: string): asserts condition {
  if (!condition) {
    throw new Error(msg || 'Assertion failed')
  }
}

const x: number | null = Math.random() > 0.5 ? 10 : null
assert(x !== null)
const y: number = x // TypeScript 现在知道 x 不可能为 null

assert 抛出错误时函数不会返回,所以执行到 assert 之后的代码时,TypeScript 能确定条件成立,进而完成类型收窄。

On this page