我的问题类似于Types from both keys and values of object in Typescript,但有一个额外的嵌套层:
interface Outer {
a: {
b: number
},
c: {
d: string
}
}
我只想检索所有值的联合类型,在number | string
。
这是我的刺路
type Values<T extends Record<string, any>> = T[keyof T]; // From previous SO answer
type InnerValues<
T extends Record<string, Record<string, any>>,
K extends keyof T
> = T[K][keyof T[K]];
type All = Values<Outer>;
type In = InnerValues<Outer, keyof Outer>; // expected number|string
但是我有一个错误,说Outer
没有索引类型。
答案 0 :(得分:2)
T[K]
将不起作用,因为T
将是K
中的所有可能值(无论如何都是keyof T[K]
指定的值)和never
的并集如果这些值没有公用键,则最终可能会变成T[K]
。
解决方案是采用联合interface Outer {
a: {
b: number;
};
c: {
d: string;
};
}
type DistributiveValues<T extends Record<string, any>> = T extends T ? T[keyof T] : never;
type InnerValues<
T extends Record<keyof T, object>,
K extends keyof T
> = DistributiveValues<T[K]>;
type In = InnerValues<Outer, keyof Outer>; // is number|string
中的每个组成部分并获取其可能的值。我们可以使用distributive conditional type
broad