我有以下代码使用接口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
吗?
答案 0 :(得分:1)
TypeScript仅对non-empty object literals执行多余的属性检查。我想这对开发人员来说通常是有益的,虽然它可能会让人感到困惑并且有一些奇怪的副作用,就像你刚刚发现的那样。
这里最简单的解决方法是显式断言空对象文字是IObject
,这样编译器就不会关闭多余的属性检查:
const fooBar: IObject = bool ? {
foo: 'not boolean',
notExisting: '132'
} : ({} as IObject); // assertion fixes it
希望有所帮助。祝你好运!