簡體   English   中英

如何有條件地在 typescript 中設置 function 參數類型?

[英]How to conditionally set a function argument type in typescript?

我有一個通用的 function 我需要在 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

可能會以完全錯誤的方式進行。 有任何想法嗎?

您可以使用 function 重載,或者使用帶有function關鍵字的重載語法,或者在您的問題中使用帶有const和箭頭 function 的接口。

重載語法:

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和箭頭 function 的 function 接口:

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);
};

游樂場鏈接

在這兩種情況下,如果Arg1Typestring並且Arg1OtherTypenumber (例如),則這些調用有效:

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 將根據 arguments 的類型推斷要使用的正確過載。 在我的示例中,類型是stringnumber When I started with functionA("foo", TypeScript could tell that I was using the string overload and will only allow a function that accepts a string. When I started with functionA(42, TypeScript could tell I was using the number overload and will只允許接受數字的 function。

對於具有不同形狀的對象也可以這樣:

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);
});

游樂場鏈接

type A = string
type B = number
type Arg1 = A | B
const functionA = (arg1: Arg1, deleteFunc: (arg1: Arg1) => void): void {
 deleteFunc(arg1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM