我有一个需要所有属性的接口。然而,创建对象是一个两步骤的过程。因此,我计划创建2个对象的“Partial”版本,然后将它们合并在一起以满足非部分接口。示例:
尽管“together”总是完整的,但编译器仍然报错:
interface IComplete {
a: string,
b: string
}
const part1: Partial<IComplete> = {
a: 'hello'
}
const part2: Partial<IComplete> = {
b: 'world'
}
const together: IComplete = {
...part1,
...part2
}
尽管“together”总是完整的,但编译器仍然报错:
Type '{ a?: string; b?: string; }' is not assignable to type 'IComplete'.
Property 'a' is optional in type '{ a?: string; b?: string; }' but required in type 'IComplete'.
有没有推荐的方法来实现这个?对于我的情况来说,很重要的一点是接口IComplete
不能被部分化,也就是说属性a和b永远不会为null或undefined。
const part1: Partial<IComplete> = ...
有什么好处。在TS 4.8中,这对我很有效。 - Arthur_J