打字稿:无效的联合类型

时间:2020-08-10 22:53:14

标签: typescript

与可选参数相比,void作为联合类型的目的是什么,它们可以互换使用吗?我期望example.func1();在以下示例中引发错误:

interface IExample
{
    num: number;
}

class Example implements IExample{
    num = 1;
    public func1(param: IExample | void){
    }

    public func2(param?: IExample){
    }
}

var example = new Example();
example.func1(); // no error - error expected
example.func2(); // no error
example.func1(example); // no error
example.func2(example); // no error

playground

1 个答案:

答案 0 :(得分:2)

我将忽略空接口问题,即任何非空值都与{}兼容。将成员添加到您的界面中,() => example调用将失败。


我认为没有任何明显的记载,但是在TypeScript中,接受void的跟踪函数参数被认为是可选的,该功能在microsoft/TypeScript#27522中实现。因此,您的两个函数的行为类似。

declare let f1: (x?: string) => string;
declare let f2: (x: string | void) => string;
f1(); // okay
f2(); // okay

此功能有些奇怪,例如,它在面对通用名称(microsoft/TypeScript#29131microsoft/TypeScript#39600)时不起作用。

尽管可以通过相同的方式进行调用,但编译器并未将上述f1f2的类型视为真正可互换的。

f1 = f2; // okay
f2 = f1; // error!

可能是因为void也是一种类型,用于从不应使用返回值的函数中返回值,从而导致这种奇怪的情况:

f1(console.log()); // error
f2(console.log()); // okay?!

该功能仅适用于功能参数;接受void的对象属性被认为是可选的(尽管甚至是suggested?)。

因此,我想说的是,您偶然发现的一种有限范围的,未完全通用的,未完全编写的,未充分记录的功能。哦,希望这有道理。祝你好运!

Playground link