簡體   English   中英

如何在 typescript 中鍵入部分應用的 function?

[英]How to type a partially applied function in typescript?

如何在不使用any的情況下正確鍵入以下 function 的返回類型? 它是一個 function,根據一個參數的存在,返回一個字符串或一個 function。

function useFetchResource(resourceType: string, id?: string): string {
    if (id) {
        return `${resourceType}:${id}`; 
    } else {
        // ERROR HERE
        return (innerId: string) => {
            return `${resourceType}:${innerId}`;
        };
    }
}

useFetchResource("products", "10");
const fetchProduct = useFetchResource("products");
// ERROR HERE
fetchProduct("10");

我試過使用重載但沒有成功:

function useFetchResource(resourceType: string): ((id: string) => string); // COMPILE ERROR: Incompatible implementation
function useFetchResource(resourceType: string, id?: string): string {

過了一段時間,許多試圖理解和使用更高級概念的嘗試都失敗了,我用 function 嘗試了同樣的方法,如果存在一個參數,它可能只返回一個數字或一個字符串,它以同樣的方式失敗:

function useFetchResource(resourceType: string): number; // COMPILE ERROR: Incompatible implementation
function useFetchResource(resourceType: string, id?: string): string {
    if (id) {
        return `${resourceType}:${id}`; 
    } else {
        return 1;
    }
}

我也嘗試過使用聯合類型的string | ((id: string) => string) string | ((id: string) => string)但它迫使 function 的消費者強制轉換值以便使用它: (fetchProduct as ((id: string) => string))("10") ,這是不是我試圖完成的。

在 typescript 中可以做類似的事情嗎?

您必須定義 function 的重載和實現。

function useFetchResource(resourceType: string): (id: string) => string;
function useFetchResource(resourceType: string, id: string): string;
function useFetchResource(resourceType: string, id?: string): string | ((id: string) => string) {
    if (id) {
        return `${resourceType}:${id}`; 
    } else {
        // ERROR HERE
        return (innerId: string) => {
            return `${resourceType}:${innerId}`;
        };
    }
}

const key = useFetchResource("products", "10");
const fetchFunction = useFetchResource("products");

// No ERROR HERE
fetchFunction("10");

暫無
暫無

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

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