A
A
Alex Mirgorodskiy2021-06-23 10:07:49
typescript
Alex Mirgorodskiy, 2021-06-23 10:07:49

How to set a conditional generic for the parameters included in the function?

Hello. I ask for help from more experienced developers.

I want to write a construction that will return a type based on what type was passed to the parameter
, nothing happens due to a lack of theory .

as if the entered data does not fall)
Please tell me how to implement this?

type C = {
    type: string
}

type A<T> = T extends C[] ? C[] : C

type Gen = <T>(a: A<T>) => A<T>

const gen: Gen = (a) => {
    return a
}

//Работает
const res = gen({
    type: 'string'
})

//Не работает
const res = gen([{
    type: 'string'
}])

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2021-07-07
@Aetae

In general, it is done simply like this:

type C = {
    type: string
}

type Gen = <T extends C | C[]>(a: T) => T

const gen: Gen = (a) => {
    return a
}

If you need to do something more complicated with a return value, then like this:
type Gen = <T extends C | C[]>(a: T) => T extends C[] ? 1 : 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question