简体   繁体   English

打字稿-带有可选参数的通用函数

[英]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. D类型检查的原因是,忽略多余的参数经常在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 . 关于参数,函数f被认为的功能的亚型g只要每个参数f是具有相应的参数兼容g Any extra arguments in f are ignored. f中的任何其他参数都将被忽略。 See 'Comparing two functions' in https://www.typescriptlang.org/docs/handbook/type-compatibility.html 请参阅https://www.typescriptlang.org/docs/handbook/type-compatibility.html中的 “比较两个函数”

(And as noted by @david-sherret, E works as you would expect, with word: string .) (正如@ david-sherret所指出的那样, E工作方式与您期望的一样,使用word: string 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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