具有条件类型的数组中的打字稿泛型

时间:2021-01-12 11:42:05

标签: typescript

假设我们有这样的代码:

const a = 'a';
const b = 'b';
type Union = typeof a | typeof b | string

interface SettingA {
  foo: 'bar';
}
interface SettingB {
  bar: 'foo';
}

type Settings<T = string> = T extends typeof a
  ? SettingA
  : T extends typeof b
  ? SettingB
  : T extends string
  ? undefined
  : never;

问题是,如果不这样做,我将如何定义一个可以具有所有这些选项的数组:

const array: Array<Settings<typeof a> | Settings<typeof b> | Settings<string>>

有没有更好的选择来做到这一点,例如这样的事情,我知道它不起作用,但仍然?:

const array: Array<Settings<Union>>

我也试过这样的:

type ValueOf<T> = T[keyof T];
type Ty = { [T in Union]: Settings<T> };
type Ty2 = ValueOf<Ty>;

但在这种情况下,Ty2 是未定义的。

编辑:似乎如果我从 Union 中删除字符串,它可以正常工作。 但是为什么会这样,我可以以某种方式使它与字符串一起工作吗?

编辑2: 正如评论中提到的那样。如果我向 Union 添加字符串,那么 TS 会将 Union 类型缩小为一个字符串。

type Union1 = 'foo' | 'bar' // 'foo' | 'bar' 
type Union1 = 'foo' | 'bar' | string // string

不幸的是,我无法解决@ford04 建议的问题,因为此联合类型/字符串也是对象中的键,其中字符串类似于 UUID。

编辑3: 似乎这是一个更广泛的问题:https://github.com/microsoft/TypeScript/issues/29729

0 个答案:

没有答案