Answer the question
In order to leave comments, you need to log in
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
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
}
type Gen = <T extends C | C[]>(a: T) => T extends C[] ? 1 : 2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question