首页 > 解决方案 > 如何在打字稿中有条件地设置函数参数类型?

问题描述

我有一个通用函数需要在 2 个地方调用

const functionA = (arg1, deleteFunction) => {
 deleteFunction(arg1)
}

当我在两个不同的地方调用它时,我deleteFunction每次都经过不同的地方。这些deleteFunctions然后更新redux,但它们需要不同的类型,所以我收到错误

我想知道是否arg1可以根据它包含的属性指定它应该是什么类型。像这样的东西

const functionA = (arg1: arg1.hasSomeProperty ? Arg1Types : Arg1OtherType, deleteFunction) => {
 deleteFunction(arg1)
}

显然这不起作用,但 2 个 deleteFunctions 有不同的类型(一个有Arg1Types另一个有Arg1OtherTypes

可能会以完全错误的方式进行。有任何想法吗?

标签: javascripttypescript

解决方案


您可以使用函数重载,或者使用带有function关键字的重载语法,或者使用带有const箭头函数的接口,就像您的问题一样。

重载语法:

function functionA(arg: Arg1Type, deleteFunction: (arg: Arg1Type) => void): void;
function functionA(arg: Arg1OtherType, deleteFunction: (arg: Arg1OtherType) => void): void;
function functionA(arg: any, deleteFunction: (arg: any) => void): void {
    deleteFunction(arg);
}

游乐场链接

const带有箭头函数的函数接口:

interface FunctionA {
    (arg: Arg1Type, deleteFunction: (arg: Arg1Type) => void): void;
    (arg: Arg1OtherType, deleteFunction: (arg: Arg1OtherType) => void): void;
}

const functionA: FunctionA = (arg: any, deleteFunction: (arg: any) => void): void => {
    deleteFunction(arg);
};

游乐场链接

在这两种情况下,如果Arg1TypestringArg1OtherTypenumber(例如),这些调用都有效:

functionA("foo", (id) => {
    // ...do the deletion...
});

functionA(42, (id) => {
    // ...do the deletion...
});

...而这些不会:

// Error: No overload matches this call.
// (because the types don't match)
functionA("foo", (id: number) => {
    // ...do the deletion...
    console.log(id);
});

// Error: No overload matches this call.
// (because no overload takes an object)
functionA({}, (id) => {
    // ...do the deletion...
    console.log(id);
});

在这两种情况下,IDE 等只会显示重载签名(前两个);实现签名不是。

在此处输入图像描述

在此处输入图像描述

在评论中你说:

...调用此函数如何知道要使用哪些类型?Arg1Type 和 Arg1OtherType 都是对象,但在这些对象内部,每个属性的类型不同。...我想进一步了解条件部分

TypeScript 将根据参数的类型推断要使用的正确重载。在我的示例中,类型是stringnumber。当我开始使用functionA("foo",TypeScript 时,可以看出我正在使用string重载,并且只允许接受字符串的函数。当我开始使用functionA(42,TypeScript 时,我可以告诉我正在使用number重载,并且只允许一个接受数字的函数。

对于具有不同形状的对象也可以这样:

interface Arg1Type {
    prop: string;
}
interface Arg1OtherType {
    prop: number;
}

functionA({"prop": "foo"}, (obj) => {
    // ...do the deletion...
    console.log(obj);
});

functionA({"prop": 42}, (obj) => {
    // ...do the deletion...
    console.log(obj);
});

游乐场链接


推荐阅读