Reputation: 873
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
}
}
Upvotes: 1
Views: 344
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;
}
}
Upvotes: 1