在TypeScript中获取双重嵌套对象的所有值类型

时间:2019-09-19 16:04:28

标签: typescript

我的问题类似于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没有索引类型。

Playground link.

1 个答案:

答案 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

play