简体   繁体   English

使用Array.map(TypeScript)返回通用数组

[英]Returning a generic array using Array.map (TypeScript)

I wrote a function that gets a string array and supposed to convert it to a T array: 我写了一个函数,它获取一个字符串数组,并将其转换为T数组:

interface Fooable {
    foo: string;
}

function simplifiedExample<T extends Fooable>(bars: string[]): T[] {
    return bars.map(bar => {
        return {
            foo: bar
        }
    })
}

But the word "bars" in the first line of the function is marked by a red line, says: 但是函数第一行中的“bars”一词用红线标出,表示:

TS2322: Type '{foo:string;}[]' is not assignable to type 'T[]'. TS2322:类型'{foo:string;} []'不能赋值为'T []'。 Type '{foo:string}' is not assignable to type 'T'. 类型“{foo:string}”不能分配给“T”类型。

How can I make it work? 我怎样才能使它工作?

You need to type assert the returned Fooable to type T : 你需要输入断言返回的Fooable来输入T

function simplifiedExample<T extends Fooable>(bars: string[]): T[] {
    return bars.map(bar => {
        return {
            foo: bar
        } as T;
    })
}

( code in playground ) 游乐场代码

The reason is that T isn't Fooable , it just extends it but might have additional properties, for example: 原因是T不是Fooable ,它只是扩展它但可能有其他属性,例如:

interface Mooable extends Fooable {
    moo: string;
}

simplifiedExample<Mooable>(["a", "b", "c"]);

In this case T is Mooable but { foo: bar } doesn't satisfy it, which is why you need to type cast. 在这种情况下, TMooable{ foo: bar }不满足它,这就是你需要输入Mooable原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM