See a playground of this question here
我有一个需要所有 Prop 的界面。但是,创建对象是一个两步过程。因此,我计划创建该对象的 2 个 Partial
版本,然后将它们合并在一起以满足非部分接口(interface)。示例:
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
接口(interface)不是是部分的,这一点很重要。 IE。 Prop a 和 b 永远不会为 null 或未定义。
最佳答案
@RyanCavanaugh 的回答很好。一种让类型推断完成其工作的方法,同时仍然获得编译器的好处确保 part1
和 part2
是 Partial<IComplete>
是使用如下辅助函数:
interface IComplete {
a: string,
b: string,
c: (x: string) => number,
d: (x: number) => string
}
// helper function
const asPartialIComplete = <T extends Partial<IComplete>>(t: T) => t;
const part1 = asPartialIComplete({
a: 'hello',
c: (x) => x.length
})
const part2 = asPartialIComplete({
b: 'world',
d: (x) => x + ""
});
const together: IComplete = {
...part1,
...part2
}
在上面,part1
和 part2
受制于 asPartialIComplete
有效Partial<IComplete>
对象(因此 c
和 d
方法的参数分别被推断为 string
和 number
)。但是 part1
的类型和 part2
足够窄,编译器可以意识到 typeof part1 & typeof part2
是IComplete
.
希望对您有所帮助。祝你好运!
关于typescript - 如何将 2 个部分合并为 Typescript 中的一个完整对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275395/