尝试使用可选参数
键入泛型函数时遇到一些问题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 ?
答案 0 :(得分:2)
D
类型检查的原因是忽略额外的参数经常在JavaScript中发生。关于参数,函数f
被认为是函数g
的子类型,只要f
的每个参数与g
的对应参数兼容即可。 f
中的任何额外参数都将被忽略。请参阅https://www.typescriptlang.org/docs/handbook/type-compatibility.html
(正如@ david-sherret所指出的,E
正如您期望的那样,word: string
正常工作。)