Conditional Return Type

I have a question. Let's say, I want to create a function that takes in 1 optional parameter arg of type T. The function also returns the value of the optional parameter.
function foo<T>(arg?: T) {
return arg
}
function foo<T>(arg?: T) {
return arg
}
In this scenario, is it possible for me to affect the return type to where it would return the value as T or as T | undefined based on whether or not arg is provided?
const test1 = foo<string>() //typeof test1 === string | undefined
const test2 = foo('string') //typeof test2 === string
const test1 = foo<string>() //typeof test1 === string | undefined
const test2 = foo('string') //typeof test2 === string
LOL forgot about function overloading... Nevermind.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?