TypeScript 对象扩展语法未触发预期类型错误的原因及解决方案咨询
TypeScript 对象扩展语法未触发预期类型错误的原因及解决方案咨询
我遇到了一个TypeScript类型检查的奇怪问题:下面这些代码片段里,我故意把address属性拼写成了addressss,按道理应该触发类型错误,但只要用到对象扩展语法(...),TypeScript就完全不报错。我已经在线上TypeScript编辑器测试过,排除了本地环境的问题,想请大家帮我搞懂这是怎么回事,同时能不能给个解决方案,让使用对象扩展语法时也能检测到这类拼写错误?
未触发错误的代码片段(使用对象扩展语法)
Snippet A.1 - 函数声明返回类型,未报错
interface TestType { company?: string; address?: string; } function testFunction(): TestType { const cond = true; const testDto = { ...(cond ? { company: '' } : {}), ...(cond ? { addressss: '' } : {}), }; return testDto; }
Snippet A.2 - 变量直接指定类型,未报错
interface TestType { company?: string; address?: string; } function testFunction() { const cond = true; const testDto: TestType = { ...(cond ? { company: '' } : {}), ...(cond ? { addressss: '' } : {}), }; return testDto; }
Snippet A.3 - 使用类型断言,未报错
interface TestType { company?: string; address?: string; } function testFunction() { const cond = true; const testDto = { ...(cond ? { company: '' } : {}), ...(cond ? { addressss: '' } : {}), }; return testDto as TestType; }
部分触发错误的代码片段
Snippet B.1 - 移除扩展语法,变量指定类型,成功报错
这个片段里我去掉了对象扩展语法,直接在变量后声明类型,TypeScript成功检测到了addressss的拼写错误:
interface TestType { company?: string; address?: string; } function testFunction() { const cond = true; const testDto: TestType = { company: '', addressss: '', }; return testDto; }
Snippet B.2 - 移除扩展语法,仅函数返回值声明类型,未报错
即使去掉了对象扩展语法,但只在函数返回值处声明TestType,TypeScript还是没报错:
interface TestType { company?: string; address?: string; } function testFunction(): TestType { const cond = true; const testDto = { company: '', addressss: '', }; return testDto; }
麻烦大家帮我解释下这背后的原因,另外能不能提供一个示例,让使用对象扩展语法时也能检测到这类属性拼写错误?非常感谢!
备注:内容来源于stack exchange,提问作者christian
相关产品推荐
相关产品推荐

