我想要作为参数给出的函数的限定类型 . 我希望这个类型是一个没有参数的函数,它返回一个包含参数的void函数(Action)或者它返回自身的void函数 .
这是我想要使用的代码:
interface JsonArray extends Array { }
interface Json {
[x: string]: string | number | boolean | Date | Json | JsonArray;
}
type Action = (arg1: string, arg2: Json | JsonArray) => void;
type ReturningAction = () => Action;
function required(arg1: string, ...validationFunctions: Array) {
console.log("Test");
}
function oneOf(arg1: string): (arg1: string, arg2: Json | JsonArray) => void {
return (arg1: string, arg2: Json | JsonArray) => {
console.log("Testing");
}
}
function notEmpty(): (arg1: string, arg2: Json | JsonArray) => void {
return (arg1: string, arg2: Json | JsonArray) => {
console.log("Empty");
}
}
required("field", oneOf); // Shouldn't be accepted
required("field", oneOf("test")) // Should be accepted
required("field", notEmpty); // Should be accepted
但是看起来,TypeScript忽略了函数定义中的额外参数而不是它预期的参数 . 这可以解决吗?
即使我做以下事情:
function required(arg1: string, ...validationFunctions: Array void>) {
console.log("Test");
}
required("field", oneOf); // Shouldn't be accepted
required("field", oneOf("test")) // Should be accepted
required("field", notEmpty); // Shouldn't be accepted
required("field", notEmpty()); // Should be accepted
由于某种原因,所有都被接受,但只有被调用的函数适用 .