为什么typescript函数重载会添加未定义的类型?

为什么typescript函数重载会添加未定义的类型?,typescript,overloading,Typescript,Overloading,我希望数据参数是字符串类型而不是字符串|未定义在类型==='scheduled'案例中。为什么会这样?有没有办法让它stringtype function foo(type: 'live'): string; function foo(type: 'scheduled', data: string): string; function foo(type: 'live' | 'scheduled', data?: string): string { switch (type) {

我希望
数据
参数是
字符串
类型而不是
字符串|未定义
类型==='scheduled'
案例中。为什么会这样?有没有办法让它
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
    }
}

这确实很奇怪,但你可以使用更有效的歧视性工会:

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

您设置了
data?:string
,因此数据类型为
string | undefined
。在函数中只使用最后一个类型定义,因此
type
的类型为
'live'|'scheduled'
数据的类型为
string | undefined
。如果您有其他信息,您可以执行以下操作,例如,
以字符串形式返回数据
。此解决方案也有一些缺陷<如果要在switch语句中使用代码>类型,则无法解构它