Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

Typescript generics in array with conditional types

Lets say we have code like this:

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;

question is, how would I define an array that can have all these options without doing like this:

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

Is there a better option to do this, like for example something this, I know it doesn't work, but still?:

const array: Array<Settings<Union>>

I also tried something like this:

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

But in this case, Ty2 is undefined.

Edit: it seems that if I remove the string from Union, it works correctly. But why is it so, and could I somehow make it work with the string?

Edit2: As in the comment it was mentioned. that if I add string to the Union then TS narrows down Union type to just a string.

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

Unfortunately, I can't resolve the problem as @ford04 suggested because this Union type/string is also key in an object where the string would be something like a UUID.

Edit3: it seems like this is a wider issue: https://github.com/microsoft/TypeScript/issues/29729


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...