【发布时间】:2023-02-03 16:37:11
【问题描述】:
将对象拆分为两个子对象的正确 Typescript 类型是什么,每个子对象都包含互补键,例如,表单的对象
{x: "x", y: "y", z:"z"}
应该拆分成一个对象
{ a: {x: "x"}, b: {y: "y", z:"z"}}.
一般记录的此对象的类型是什么?
我试过这个,但它给了我一个错误:
type Split<Union extends Record<string, string | number>>= <A extends Partial<Union>>() => {
a: A,
b: Omit<Union, keyof A>
};
type SpecificUnion = {
x: string
y: number
z: string
}
const split: Split<SpecificUnion> = () => {
return {
a: { x: "x" },
b: { y: "y", z: "z"}
}}
我得到错误
Type '() => { a: { x: string; }; b: { y: string; z: string; }; }' is not assignable to type 'Split<SpecificUnion>'.
Call signature return types '{ a: { x: string; }; b: { y: string; z: string; }; }' and '{ a: A; b: Omit<SpecificUnion, keyof A>; }' are incompatible.
The types of 'a' are incompatible between these types.
Type '{ x: string; }' is not assignable to type 'A'.
'{ x: string; }' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype of constraint 'Partial<SpecificUnion>'.
这个错误似乎自相矛盾,因为它说“'{ x: string; }' is not assignable to type 'A'”和“'{ x: string; }' is assignable to the constraint of type 'A'”。
【问题讨论】:
-
错误消息说
A extends Partial<Union>可以是{ x: string },但也可以是{ y: number }。或者{ x: string; y: number}。对于A的不同值,您得到Split<SpecificUnion>的不同定义,但是Split<Union>没有被A参数化,因此它不应该依赖于A的定义。 -
"y"不是数字。
标签: typescript