Answer the question
In order to leave comments, you need to log in
How to create a generic conditional type in Typescript?
Hello!
The problem is: Let's say I want to create a Creature type with the properties:
- type,
- subtype,
- params
And in case I declare type = 'People', the subtype must be of type: 'adult' | 'child'.
If subtype = 'child', params should be {age: number; school: string;}
If subtype = 'adult', params must be of type {height: number, weight: number, age: number}
Thus, I want to do type = 'animal', subtype = 'fish' | 'cat'. And depending on the subtype, assign the type to the params property.
What for? To then declare, for example, the creatures: Creature[] array, in which to cram objects of the same type, with different types property.
How can this be implemented in TS'e, except for the usual enumeration with such a wand: "|".
Also, I will be grateful for suggestions on how to get around this, but at the same time, so that some kind of dependent type check is saved.
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
If type and subtype are strings, then you can do this:
type CreatureBasis = {
People: {
child: {
age: number;
school: string;
};
adult: {
age: number;
height: number;
weight: number;
};
};
Animal: {
fish: {
waterBody: string;
};
cat: {
catchMouses: boolean;
};
};
};
type Creature = {
[K0 in keyof CreatureBasis]: {
[K1 in keyof CreatureBasis[K0]]: {
type: K0;
subtype: K1;
params: CreatureBasis[K0][K1];
};
}[keyof CreatureBasis[K0]];
}[keyof CreatureBasis];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question