zimex
zimex

Reputation: 873

Why typescript function overload adds undefined type?

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

Upvotes: 1

Views: 344

Answers (1)

Nino Filiu
Nino Filiu

Reputation: 18493

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

Upvotes: 1

Related Questions