Typescript - 带有可选参数

时间:2017-09-25 13:52:49

标签: typescript generics

尝试使用可选参数

键入泛型函数时遇到一些问题
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 个答案:

答案 0 :(得分:2)

D类型检查的原因是忽略额外的参数经常在JavaScript中发生。关于参数,函数f被认为是函数g的子类型,只要f的每个参数与g的对应参数兼容即可。 f中的任何额外参数都将被忽略。请参阅https://www.typescriptlang.org/docs/handbook/type-compatibility.html

中的“比较两个函数”

(正如@ david-sherret所指出的,E正如您期望的那样,word: string正常工作。)