简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM