[英]How to avoid unnecessary arguments when using optional generic type in TypeScript?
StateFunction 有一个可选的(第二个)泛型类型——因为它有一个默认值。 问题是,如果我不通过第二个泛型,我仍然必须将undefined
作为参数,即使我认为此时它是可选的。
使用 args 使args
可选args?
确实有帮助,但它强制检查空值,即使强硬类型也不能为空。
我也可以使 function 过载,但这不是最佳的,因为我使用的真正 function 相当长。
在未指定第二个泛型的情况下,是否有真正的解决方案可以使该论点消失?
interface StateFunctionAction<T, P> {
(saved: T, args: P): void
}
const StateFunction = <T, P = undefined>(value : T, action: StateFunctionAction<T, P>) => {
let saved = value;
return (args : P) => action(saved, args);
}
const example1 = StateFunction<string>("Hello World", (saved) => console.log(saved))
example1(); // Help -> An argument for 'args' was not provided.
const example2 = StateFunction<string, number>("Hello World", (saved, n) => console.log(saved + " " + n))
example2(5);
不要使用undefined
作为默认泛型类型,而是使用void
。 这将使争论消失。
const StateFunction = <T, P = void>(value : T, action: StateFunctionAction<T, P>) => {
let saved = value;
return (args : P) => action(saved, args);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.