有人知道为什么 Typescript 没有提示缺少 c
吗?
type MyType = {a: number, b: number, c: number}
const Defaults = {myDefault: {a: 5, b: 6} as MyType}
如果我有
const Defaults = {myDefault: {a: 5, b: 6, d: 9} as MyType}
它提示 c
是一个缺失的属性(而不是提示 d 未知)。但如果我只有 ab
或 abcd
,它就不会提示。
添加 required
也不会改变任何内容。
const Defaults = {myDefault: {a: 5, b: 6} as Required<MyType>}
为什么会这样?
最佳答案
David Scholz 的答案似乎是正确的,但我认为在这种情况下您可能更愿意不使用 as
运算符。如果您完全键入变量 Defaults
,TypeScript 会提示 c
未按预期指定:
type MyType = {a: number, b: number, c: number}
type DefaultsType = {myDefault: MyType};
const defaults: DefaultsType = {myDefault: {a: 5, b: 6}}
关于Typescript 不会提示缺少或太多对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71193992/