TypeScript: use of generic and union types

十年热恋 提交于 2021-01-29 04:08:20

问题


I have code which uses function overload, something like:

function f0(v: Object): void { }

function f1(a: number, b: number): void;
function f1(a: string, b: string): void;
function f1(a: any, b: any): void {
    f0(a); // OK
}

That I would like to convert using union types, but I get an error:

function f1<T extends number | string>(a: T, b: T): void {
    f0(a); // Error: Argument of type 'T' is not assignable to parameter of type 'Object'.
}

What's wrong here, knowing that the following is OK:

function f2(v: number | string) {
    f0(v);
}
function f3<T extends number>(v: T) {
    f0(v);
}
function f4<T extends string>(v: T) {
    f0(v);
}

回答1:


I finally asked to MS and it seems to be a bug: https://github.com/Microsoft/TypeScript/issues/2576



来源:https://stackoverflow.com/questions/29355643/typescript-use-of-generic-and-union-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!