Returning a generic array using Array.map (TypeScript)

Question

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?


Show source
| javascript   | arrays   | oop   | typescript   | generics   2017-01-02 10:01 1 Answers

Answers to Returning a generic array using Array.map (TypeScript) ( 1 )

  1. 2017-01-02 11:01

    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.

Leave a reply to - Returning a generic array using Array.map (TypeScript)

◀ Go back