簡體   English   中英

推斷 typescript function arguments

[英]Infer typescript function arguments

鑒於以下

const action1 = (arg1: string) => {}
const action2 = (arg1: string, arg2: {a: string, b: number}) => {}
const actions = [action1, action2]
handleActions(actions)

... elsewhere ...

const handleActions = (actions: WhatTypeIsThis[]) => {
  const [action1, action2] = actions;
  action1(/** infer string */)
  action2(/** infer string and object */)
}

如何定義WhatTypeIsThis類型以使操作 args 在handleActions中可推斷?

是否可以將其定義為actions可以是具有不同參數列表的任意數量的函數?

是否可以使用 generics?

是否可以將其定義為動作可以是具有不同參數列表的任意數量的函數?

使用動態列表,您需要運行時檢查。 我不認為你可以在不標記它們的情況下對這些函數進行運行時檢查(我嘗試對length進行檢查,因為這兩個函數有不同的長度,但它不起作用,即使它確實沒有用— (arg1: string) => void(arg1: number) => void是具有相同length的不同函數)。

通過品牌和運行時檢查,可以:

  • 定義功能的品牌類型
  • 創建函數
  • 將動作列表定義為 function 類型的聯合數組
  • 在品牌上有handleActions分支

像這樣:

type Action1 = (
    (arg1: string) => void
) & {
    __action__: "action1";
};

type Action2 = (
    (arg1: string, arg2: {a: string, b: number}) => void
) & {
    __action__: "action2";
};

const action1: Action1 = Object.assign(
    (arg1: string) => {},
    {__action__: "action1"} as const
);
const action2: Action2 = Object.assign(
    (arg1: string, arg2: {a: string, b: number}) => {},
    {__action__: "action2"} as const
);

const actions = [action1, action2];

type ActionsList = (Action1 | Action2)[];

const handleActions = (actions: ActionsList) => {
    const [action1, action2] = actions;
    if (action1.__action__ === "action1") {
        action1("x");   // <==== infers `(arg: string) => void` here
    }
};  

handleActions(actions);

游樂場鏈接


添加答案頂部引用的文本之前,可以使用 readonly tuple type 我將其保留在答案中,以防它對其他人有用,即使它不適用於您的情況。

看起來是這樣的:

type ActionsList = readonly [
    (arg1: string) => void,
    (arg1: string, arg2: { a: string; b: number; }) => void
];

要使其只讀,您需要as const on actions

const actions = [action1, action2] as const;
//                                ^^^^^^^^^

元組是一種“...數組類型,它確切地知道它包含多少元素,以及它在特定位置包含哪些類型。” (來自上面的鏈接)

游樂場鏈接

暫無
暫無

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

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