V
V
veryoriginalnickname2021-10-30 01:23:36
typescript
veryoriginalnickname, 2021-10-30 01:23:36

Type depending on value?

There is a type:

export type THook = {
    name: "onRequest" | "onResponse"
    data: string
}

Is it possible to make data type dependent on name? That is, if name === "onRequest", then data must be a number, if name === "onResponse", then data must be a string. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-10-30
@veryoriginalnickname

https://www.typescriptlang.org/docs/handbook/union...

export type THook = {
    name: 'onRequest';
    data: number;
} | {
    name: 'onResponse';
    data: string;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question