简体   繁体   中英

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:

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:

TS2322: Type '{foo:string;}[]' is not assignable to type 'T[]'. Type '{foo:string}' is not assignable to type 'T'.

How can I make it work?

You need to type assert the returned Fooable to type 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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