簡體   English   中英

返回參數類型為傳入 function 參數值的函數的 object

[英]Return object of functions with argument types of incoming function argument values

我想要 function,我們稱之為DummyService ,它將接受一些definition object 作為參數,並以DummyService的方式返回一堆函數,這些函數只能作為參數返回。 請參閱下面的代碼示例。 知道如何實現這一目標嗎? 提前非常感謝。

type Definition = {
    id: string;
    steps: Array<{key: string, callback?: () => void}>
};

const DummyService = (definition: Definition) => {
    return { 
        dummyFn: (step: {key: any}) => { // I need to figure out the type that would allow to pass only certain values that has been passed in `steps` array of `definition`
            console.log(step);
        }
    };
};

const DummyComponent1 = () => {
    const definition = {
        id: "testId1",
        steps: [
            {  key: "key1"},
            {  key: "key2"},
        ],
    };

    const { dummyFn } = DummyService(definition);
    const handler = () => dummyFn({ key: "key1dsfasd" }); // I want this to be invalid - valid key values should be only "key1" or "key2"

    return <div onClick={handler}>test</div>;
}

const DummyComponent2 = () => {
    const definition = {
        id: "testId2",
        steps: [
            {  key: "key3"},
            {  key: "key4"},
        ],
    };

    const { dummyFn } = DummyService(definition);
    const handler = () => dummyFn({ key: "key3" }); // This should be valid - valid key values should be only "key2" or "key4"

    return <div onClick={handler}>test</div>;
}```

我們需要使Definition成為依賴於步驟數組的泛型。

這里棘手、混亂的部分是處理像"key1""key2"這樣的字符串作為它們的字面值,而不僅僅是類型string 為此,我們必須在definition后添加as const

const definition = {/*...*/} as const;

這將值解釋為文字字符串,但它也使定義中的所有內容為readonly 所以我們需要在定義DefinitionDummyService的類型時添加一堆readonly否則我們會得到關於將readonly分配給可變類型的錯誤。

定義如下:

type Definition<Steps extends readonly {key: string, callback?: () => void}[]> = {
    readonly id: string;
    readonly steps: Steps;
};

我們說我們的Steps extends了一個數組,我們希望它是一個特定的元組。

我們的DummyService如下所示:

const DummyService = <Steps extends readonly {key: string, callback?: () => void}[]>(definition: Definition<Steps>) => {
    return { 
        dummyFn: (step: { key: Steps[number]['key'] }) => {
            console.log(step);
        }
    };
};

Steps[number]['key']類型為我們提供了所有有效的步驟鍵。 作為旁注,我不確定您為什么要傳遞您的參數,例如({key: "key2"})而不僅僅是("key2")

您現在得到所有需要的錯誤,並且正確調用時沒有錯誤。

Typescript 游樂場鏈接

暫無
暫無

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

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