Typescript泛型类型不可赋值错误

时间:2018-02-22 07:33:41

标签: typescript

尝试创建通用但显示错误:输入"用户[]"不能分配给类型T [] 无法理解这样做有什么不妥 -

interface User {
    name: string,
    age: number
}

interface Movie {
    title: string,
    language: string
}

function getItems<T>(arg: number|string): T[] {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
        return useList;
    } else {
        return movieList;
    }
}

var a: User[] = getItems<User>('user_list');

2 个答案:

答案 0 :(得分:2)

您应该为您的案例使用函数重载而不是泛​​型。

请注意,编译器将隐藏函数的签名。

function getItems(arg: string): User[];
function getItems(arg: number): Movie[];
function getItems(arg: number | string) {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
        return useList;
    } else {
        return movieList;
    }
}

var a = getItems('user_list');

答案 1 :(得分:2)

问题是你的功能并不是真正的通用。使用泛型参数时,无法返回特定类型,需要遵守传递给您的泛型参数。能够做你想要的功能签名就是使用重载的功能签名

[DllImport("Test.dll", CharSet = CharSet.Unicode, SetLastError = true ,CallingConvention = CallingConvention.StdCall)]
    public static extern int TestMethod (
        bool isSuccess,
        [In, Optional] int UsernmaeLength,
        out string userName
    );
    //Caller
    bool isSuccess = false;
    Wrapper. TestMethod (isSuccess, 200, out userName);
相关问题