1

I'm expecting data argument to be string type not string | undefined in type === 'scheduled' case. Why this is happening? Is there a way to make it string type?

function foo(type: 'live'): string;
function foo(type: 'scheduled', data: string): string;
function foo(type: 'live' | 'scheduled', data?: string): string {

    switch (type) {
        case 'live':
            return '';
        case 'scheduled':
            return data; // expecting for this to be string type not string | undefined
    }
}

Playground Link

2
  • 1
    you set data?: string, so type of data is string | undefined. Commented Jun 23, 2020 at 8:34
  • Inside the function only the last type definition is used, so the type of type is 'live' | 'scheduled' and the type of data is string | undefined. Given that you have additional information, you could do e.g. return data as string. Commented Jun 23, 2020 at 8:35

1 Answer 1

1

It's weird indeed, but you can use discriminated unions which work better:

function foo(t: { type: 'live' } | { type: 'scheduled', data: string }): string {
    switch (t.type) {
        case 'live':
            return '';
        case 'scheduled':
            t.data;
    }
}

Playground Link

Sign up to request clarification or add additional context in comments.

1 Comment

This solution also has some gotchas to it. type can't be deconstructed if you want to use it in switch statement Playground Link

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.