You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TypeScript编译器未检测到可选属性调用toFixed()的错误?

问题:TypeScript未在编译阶段捕获可选属性的空值调用错误

我在VS Code中编写了如下TypeScript代码:

function car (car: {
    make: string,
    model: string,
    year: number,
    chargeVoltage?: number
}){
    console.log(`${car.model} was made by ${car.make} in year ${car.year} ${car.chargeVoltage.toFixed(2)}`)
}

car({
    make: 'Ford',
    model: 'Fortuner',
    year: 1997
})

问题在于,chargeVoltage是可选属性,直接调用其toFixed()方法时,TypeScript编译器未抛出类型错误,仅在运行时出现报错。这类空值调用错误本应在编译阶段就被捕获。

以下是我的项目配置文件:

package.json

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "Repo focussed on learning typescript",
  "main": "src",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "tsc --watch --preserveWatchOutput"
  },
  "author": "Atul Singh",
  "license": "ISC",
  "dependencies": {
    "nodemon": "^2.0.22",
    "tsc": "^2.0.4",
    "typescript": "^5.1.6"
  },
  "devDependencies": {
    "concurrently": "^8.2.0",
    "ts-node": "^10.9.1"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2017", // which level of js support to target
        "outDir": "dist",    // where to put the ts file
       
    },
    "include": ["src"]
}

原因与解决方案

TypeScript默认未开启严格空值检查规则,因此对于可能为undefined的可选属性,编译器不会强制要求你处理空值场景。要让编译器捕获这类错误,需在tsconfig.json中启用严格模式或单独开启strictNullChecks选项。

1. 修改tsconfig.json配置

更新compilerOptions,添加strict: true(推荐,开启所有严格检查规则),或单独设置strictNullChecks: true:

{
    "compilerOptions": {
        "target": "ES2017",
        "outDir": "dist",
        "strict": true // 开启严格模式,包含strictNullChecks
        // 或单独启用:"strictNullChecks": true
    },
    "include": ["src"]
}

开启后,编译器会直接提示chargeVoltage可能为undefined,无法直接调用toFixed()方法。此时你需要通过以下方式处理空值:

2. 空值处理方案

  • 可选链操作符+默认值:
console.log(`${car.model} was made by ${car.make} in year ${car.year} ${car.chargeVoltage?.toFixed(2) || 'N/A'}`)
  • 提前判断属性存在性:
const voltageText = car.chargeVoltage ? car.chargeVoltage.toFixed(2) : '无电压数据';
console.log(`${car.model} was made by ${car.make} in year ${car.year} ${voltageText}`)
  • 空值合并运算符设置默认值:
function car (car: {
    make: string,
    model: string,
    year: number,
    chargeVoltage?: number
}){
    const voltage = car.chargeVoltage ?? 0; // 若属性不存在则默认设为0
    console.log(`${car.model} was made by ${car.make} in year ${car.year} ${voltage.toFixed(2)}`)
}

内容的提问来源于stack exchange,提问作者Atul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:00:01