Returning a shared array using Array.map (TypeScript)

I wrote a function that receives a string array and must 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 with a red line, says:

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

How can I make it work?

+5
source share
1 answer

You need to enter assert Fooable to type T :

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

( code on the playground )

The reason is that T not Fooable , it just extends it, but may 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 } does not satisfy this, so you need to enter cast.

+4
source

Source: https://habr.com/ru/post/1262167/


All Articles