antoinestv
antoinestv

Reputation: 3306

Typescript - Generic function with an optional parameter

I have some trouble trying to type a generic function with an optional parameter

type Action<TParameters = undefined> = (parameters: TParameters) => void

const A: Action = () => console.log('Hi :)') 
// Ok, as expected

const B: Action<string> = (word: string) => console.log('Hello', word)  
// Ok, as expected

const C: Action<string> = (word: number) => console.log('Hello', word)  
// Error, as expected

const D: Action<string> = () => console.log('Hello')  
// Hum, what ?!? No error ?

const E: Action<string> = (word) => console.log('Hello', word)  
// No error as expected but the type inference of `word` is `any`, why ?

Test it yourself

Upvotes: 0

Views: 359

Answers (1)

Oblosys
Oblosys

Reputation: 15096

The reason why D type checks is that ignoring extra parameters happens often in JavaScript. With regard to the parameters, a function f is considered a subtype of a function g as long as each parameter of f is compatible with the corresponding parameter of g. Any extra arguments in f are ignored. See 'Comparing two functions' in https://www.typescriptlang.org/docs/handbook/type-compatibility.html

(And as noted by @david-sherret, E works as you would expect, with word: string.)

Upvotes: 2

Related Questions