5

I noticed a difference in how the arguments are type-checked between the different syntax of function types in TypeScript.

type TypeA = {
  callback(value?: string): void,
}

type TypeB = {
  callback: (value?: string) => void,
}

function foo (value: string) {}

const a: TypeA = {
 // No error
 callback: foo,
}

// Property 'callback' is missing in type '{}'
// but required in type 'TypeA'
const a2: TypeA = {
}

const b: TypeB = {
  // Type '(value: string) => void' is not assignable to
  // type '(value?: string | undefined) => void'.
  callback: foo,
}

Here's the typescript playground link

The call signature function type happily accepts a function with param value: string, while the function type expression complaints that it is not exactly value: string | undefined.
I would've expected a type error in both the cases.

Why is the call signature syntax more relaxed about the argument type?

varmundi
  • 51
  • 4
  • 1
    Also check the section about methods here: https://stackoverflow.com/questions/66410115/difference-between-variance-covariance-contravariance-and-bivariance-in-typesc – Tobias S. Dec 16 '22 at 23:36
  • Thanks, @TobiasS. that explains it clearly! – varmundi Dec 17 '22 at 00:25

0 Answers0