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
}
}
data?: string, so type of data isstring | undefined.typeis'live' | 'scheduled'and the type ofdataisstring | undefined. Given that you have additional information, you could do e.g.return data as string.