Reputation: 3518
Here is playground
I am trying to make a parameter optional, but still make typescript understand what will get returned from function.
If param is defined, then type of param is returned. Otherwise - if no param is provided, function will return undefined.
const meh = <T>(initialData?: T): { data: T | undefined} => {
if (initialData) {
return { data: initialData }
}
return {
data: undefined
}
}
const res1: undefined = meh().data // is ok:
type ResType = {
hello: string
}
const res2: ResType = meh<ResType>({ hello: 'hello'}).data.hello // TS error: Object is possibly undefined
Which makes sense. Though, I found conditional types and I though I could do something like
const meh = <T>(initialData?: T): { data: T ? T : undefined} => {
, but it gives syntax error.
Upvotes: 0
Views: 136
Reputation: 10209
Could you use function overloads?
function meh(): { data: undefined };
function meh<T>(initialData: T): { data: T };
function meh<T>(initialData?: T): any {
if (initialData) {
return { data: initialData }
}
return {
data: undefined
}
}
type ResType = {
hello: string
}
const res1: ResType = meh<ResType>({ hello: 'hello'}).data
const res2: undefined = meh().data
Upvotes: 1