0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I never used them before. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.