skip to content

TypeScript
TS 中尽量不要使用非空断言

未编译的 TS 代码

interface Person {
  name?: string
  age?: number
}

const p: Person = {}
p.age?.toFixed()
p.age!.toFixed()

编译的 JS 代码

'use strict'
var _a
const p = {}
;(_a = p.age) === null || _a === void 0 ? void 0 : _a.toFixed()
p.age.toFixed()

可以看出使用非空断言,当 p 没有 age 属性的时候掉用 .toFixed() 是会报错的