Array.prototype.map.call() has a return type of unknown[]

Viewed 366

I'm writing a function that accepts an array-like object and converts it to an array of numbers. However, TypeScript 3.9.7 does not infer the return type of Array.prototype.map.call() - it believes that it returns unknown[].

let input: string[] = ["1", "2", "3"];
// OK
let result1: number[] = input.map(str => Number(str));
// error TS2322: Type 'unknown[]' is not assignable to type 'number[]'
let result2: number[] = Array.prototype.map.call(input, str => Number(str));

I want TypeScript to infer the type of result2 from that of my callback (str => Number(str)). What can I do, apart from from using type assertions?

Edit: I am using the --strict compiler option.

1 Answers

If you use --strict option, the call function will be define as

call<T, A extends any[], R>(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R;

as you can see, R now is return type.

For your example, you can set R to be number[]

let result2 = Array.prototype.map.call<string[], any[], number[]>(input, (str: string) => Number(str));

Now, result2 is a number[].

Related