Home > OS >  Unable to assign (data: number) => void to (data: unknown) => void
Unable to assign (data: number) => void to (data: unknown) => void

Time:07-16

type NumFunc = (data: number) => void;
type UnknownFunc = (data: unknown) => void;

declare let numFunc: NumFunc;
let unknomnFunc: UnknownFunc = numFunc
    ~~~~~~~~~~~

Error:

Type 'NumFunc' is not assignable to type 'UnknownFunc'.
  Types of parameters 'data' and 'data' are incompatible.
    Type 'unknown' is not assignable to type 'number'.

What??? I'm assigning number to unknown, why is it suddenly trying to assign unknown to number now?

Playground

CodePudding user response:

Let's be a little more verbose: expand

let unknomnFunc: UnknownFunc = numFunc;

into

let unknomnFunc: UnknownFunc = x => numFunc(x);

We're taking an unknown argument x (because that's what UnknownFunc eats) and, without any type checking, use it as an argument of a NumFunc. Hence the protest. Do some type checking

let unknomnFunc: UnknownFunc = x => typeof x === 'number'
    ? numFunc(x)
    : void 0;

or declare "I know better" with type assertion

let unknomnFunc: UnknownFunc = x => numFunc(x as number);

Note that the errors also go away, when you replace unknown with any. That's the advantage of using unknown: you actually need to do something about type-unsafe operations, instead of charging "Leeroy Jenkins!"-style (as any allows you).

CodePudding user response:

Since (data: unknown) => void changes the parameter type to accept any type, the two function types aren't compatible.

numFunc('foo') // has type error
unknownFunc('foo') // does not have type error

If unknown was in the return type, it should be fine to change the type.

  • Related