我在用[电子邮件受保护] /cdn-cgi/l/email-protection.
我有一个目标对象:
interface MyTarget {
a: string;
b: string;
c: string;
d: string;
}
我想使用泛型创建部分对象的多个转换。
一种这样的转换可能如下所示:
const convert = <T extends object>(t: T): MyTarget => {
return {
c: "c",
d: "d",
...t,
};
};
然而这会导致:
error TS2698: Spread types may only be created from object types.
即使我守护通用T
成为一个object
.
然后我想起来有一个Partial
类型,因此我尝试了这个:
const convert = (partial: Partial<MyTarget>): MyTarget => {
return {
c: "c",
d: "d",
...partial,
};
};
Yet the Partial
使所有属性可选。我不想要这样,它现在会抛出:
src/Partial.ts(14,5): error TS2322: Type '{ a?: string; b?: string; c: string; d: string; }' is not assignable to type 'MyTarget'.
Property 'a' is optional in type '{ a?: string; b?: string; c: string; d: string; }' but required in type 'MyTarget'.
我想创建一个实例MyTarget
每个字段都设置为要求。我确实想保持类型安全,这就是为什么我不想这样做,即使它有效:
const convert = (partial: Partial<MyTarget>): MyTarget => {
return {
c: "c",
d: "d",
...partial,
} as MyTarget; // loses type checks, really don't want to
};