0

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

1
  • word is string in the final example you posted (see the test it yourself link). Commented Sep 25, 2017 at 14:09

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.