P
P
Persotr272021-06-25 15:10:55
typescript
Persotr27, 2021-06-25 15:10:55

How to get property types of a combined type in TypeScript?

Hello!

It is better to show the problem with an example, so here ... I have such a combined type

type Creature = {
    type: "people";
    subtype: "adult";
    params: IPeopleAdultParams;
} | {
    type: "animal";
    subtype: "cat";
    params: IAnimalCatParams;
}


There is an array:
const creatures = Creature[];

Instead of constantly writing something like
creatures.push({
type: 'animal', 
subtype: 'cat',
params: {
...
}});

I want to use the push(type, subtype, params) function, which will execute the code above with the arguments passed to it.
For example, push('people', 'adult', {...});
Approximate view of the function:
function push(type: ?, subtype: ??, params: ???) {
    creatures.push({type, subtype, params})
}


The subtype type is different depending on the type type (well, you can see it by the Creature type definition), also the params type itself depends on the type & subtype types.

How to set the argument types for the push function?
Thank you in advance! :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2021-06-25
@Kozack

type Creature = {
    type: "people";
    subtype: "adult";
    params: IPeopleAdultParams;
} | {
    type: "animal";
    subtype: "cat";
    params: IAnimalCatParams;
}

type allTypes = Creature['type']

playground

D
Dmitry Belyaev, 2021-06-29
@bingo347

When I answered you here in the example there was a CreatureBasis type from which the Creature type was already built through calculations on types.
You can also use it to build your function:
https://www.typescriptlang.org/play?#code/C4TwDgpg...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question