Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 272
Alon Avatar asked Jan 02 '17 09:01

Alon


Video Answer


1 Answers

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.

like image 186
Nitzan Tomer Avatar answered Sep 20 '22 13:09

Nitzan Tomer