首页 文章

打字稿:隐式没有参数函数类型

提问于
浏览
3

我想要作为参数给出的函数的限定类型 . 我希望这个类型是一个没有参数的函数,它返回一个包含参数的void函数(Action)或者它返回自身的void函数 .

这是我想要使用的代码:

interface JsonArray extends Array<string | number | boolean | Date | Json | JsonArray> { }

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<ReturningAction | Action>) {
    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<(arg1: string, arg2: Json | JsonArray) => 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

由于某种原因,所有都被接受,但只有被调用的函数适用 .

1 回答

  • 1

    我认为你注意到,TypeScript allows你传递一个参数较少的函数(例如, oneOf() 接受一个参数)到需要更多参数函数的东西(在这种情况下, validationFunctions[0] 应该采用两个参数,假设它是 Action ) . 这是因为函数总是可以自由地忽略传入的额外参数,并且导致错误会导致其他地方出现恼人的错误(正如TypeScript FAQ的链接部分所解释的那样) .

    编辑:以下假设您正在使用 strictNullChecks 编译器选项 .

    一种解决方法是声明 oneOfnotEmpty 函数,使它们正常工作,但不能解释为 Action 值:

    function oneOf(arg1: string, nope?: never): (arg1: string, arg2: Json | JsonArray) => void {...}
    
    function notEmpty(nope?: never): (arg1: string, arg2: Json | JsonArray) => void {...}
    

    请注意,在每种情况下都添加了 nope 参数 . 现在你应该在你期望的地方得到错误 . 由于 nope 是一个可选参数,您可以将其保留,因为它的类型为 never ,您几乎不得不将其遗漏 . 所以它并没有真正改变函数的使用方式 .


    还有其他修复,但它们更重...例如,您可以使 ActionReturningAction 包含您要调用的函数的非函数类型 .

    希望有所帮助 .

相关问题