Home > Enterprise >  Make sense of the error message "Type 'unknown' is not assignable to type 'strin
Make sense of the error message "Type 'unknown' is not assignable to type 'strin

Time:12-22

Here is my isolated code:

type IDontCare = any;

let aFunction: (params: unknown) => IDontCare;
aFunction = (hello: string) => 0;

And I got the error message Type 'unknown' is not assignable to type 'string'. I wonder, isn't it I'm trying to assign 'string' to 'unknown' instead? I can't wrap my head around this error message, and would love to hear some explanation. Thanks.

Code Error message
enter image description here enter image description here

CodePudding user response:

When you say (params: A) => number is assignable to (params: B) => number, you expect (params: A) => number behaves the same as (params: B) => number,

i.e. (params: A) => number can take a params of type B and return a number.

That means you are trying to check if a B can be passed into (params: A) => number. The result is you are trying to assign B to A. If B is not assignable to A, then (params: A) => number is not assignable to (params: B) => number.

In other words, you need B to be assignable to A in order for (params: A) => number to be assignable to (params: B) => number

CodePudding user response:

Type of aFunction says, that it can receive argument of any type. So, you should assign to aFunction function that can do the same or even more.

(hello: string) => 0 cannot take any argument (actually, it takes only string), so it is not assignable to aFunction

  • Related