TypeScript 三元运算符隐藏类型错误 - 如何重写以使用类型检查?
TypeScript ternary operator hides type error - how to rewrite to use typecheck?
我有以下代码使用接口 IObject
:
interface IObject {
foo?: boolean;
}
const bool = true;
const fooBar: IObject = bool ? {
foo: 'not boolean', // should be boolean only
notExisting: '132' // should not exist
} : {}; // only this type is considered to be returned
代码的问题在于,即使它在所有地方都有严格的类型,也有可能填写错误的对象。
看起来是基于 TypeScript 的问题 on this
我的问题是编写这样的代码的最佳方式是什么,但要保持类型安全?
不使用 let
可以这样做吗?
TypeScript 仅在 non-empty object literals 上执行额外的 属性 检查。我想,这通常对开发人员有益,尽管它可能会造成混淆并产生一些奇怪的副作用,就像您刚刚发现的那样。
这里最简单的解决方法是显式断言空对象文字是一个 IObject
,这样编译器就永远不会关闭多余的 属性 检查:
const fooBar: IObject = bool ? {
foo: 'not boolean',
notExisting: '132'
} : ({} as IObject); // assertion fixes it
希望对您有所帮助。祝你好运!
我有以下代码使用接口 IObject
:
interface IObject {
foo?: boolean;
}
const bool = true;
const fooBar: IObject = bool ? {
foo: 'not boolean', // should be boolean only
notExisting: '132' // should not exist
} : {}; // only this type is considered to be returned
代码的问题在于,即使它在所有地方都有严格的类型,也有可能填写错误的对象。
看起来是基于 TypeScript 的问题 on this
我的问题是编写这样的代码的最佳方式是什么,但要保持类型安全?
不使用 let
可以这样做吗?
TypeScript 仅在 non-empty object literals 上执行额外的 属性 检查。我想,这通常对开发人员有益,尽管它可能会造成混淆并产生一些奇怪的副作用,就像您刚刚发现的那样。
这里最简单的解决方法是显式断言空对象文字是一个 IObject
,这样编译器就永远不会关闭多余的 属性 检查:
const fooBar: IObject = bool ? {
foo: 'not boolean',
notExisting: '132'
} : ({} as IObject); // assertion fixes it
希望对您有所帮助。祝你好运!