P
P
Persotr272021-06-22 23:00:46
typescript
Persotr27, 2021-06-22 23:00:46

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

1 answer(s)
D
Dmitry Belyaev, 2021-06-24
@Persotr27

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];

https://www.typescriptlang.org/play?#code/C4TwDgpg...
TypeScript was created to type any game that can be found in the dynamic world of JavaScript. As a result, it has a Turing complete type system, from which there are 2 consequences:
1. with due diligence, you can type any Wishlist
2. some especially fancy types can hang a typechecker

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question