Uncertain about how to phrase this inquiry. I have a specific situation where an object is involved. Key1 represents the name, while key2 stands for options. The type of options is determined by the value of the name.
The existing solution works fine thanks to:
export type Option1 = {
one: string;
};
export type Option2 = {
two: string;
};
export type Name = 'first' | 'second';
export type Options<TName extends Name> = TName extends 'first'
? Option1
: TName extends 'second'
? Option2
: never;
type Baz<TName extends Name> = { name: TName, opts: Options<TName> }
Now, my intention is to utilize this in an object.
type MyObj = {
foo: boolean,
bar: string,
baz: Baz[]
}
The objective is to achieve something similar to this:
const test: MyObj = {
baz: [ { name: 'first': opts: .. }, { name: 'second': opts: .. }]
}
Ensuring everything is typed correctly. When name
is 'first', then opts
should only contain the key one
. However, MyObj
raises an issue that requires passing a generic type to Baz, which is logical but confusing. I attempted using
type Baz<TName extends Name = Name>
to set a default, yet it resulted in all values becoming a union of both options, where opts contains keys one
and two
.
How can I limit this type?