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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With