簡體   English   中英

如何使用提供的參數推斷 function 的返回類型?

[英]How can infer return type of a function using the parameters supplied?

我有一個通用的 function,其返回類型基於輸入類型。 如何根據提供的參數正確確保返回類型的類型安全?

例子




interface IKeyboardService{
    type() : void;
}

class KeyboardService{
    type(){
        
    }
}

interface IMouseService{
    move() : void;
}

class MouseService{
    move(){

    }
}

interface ServiceTypeMapping{
    Keyboard: IKeyboardService,
    Mouse: IMouseService
}

type ServiceType = keyof ServiceTypeMapping;

function getService<T extends ServiceTypeMapping, K extends keyof ServiceTypeMapping>(serviceType : K): typeof T[K]{
    switch(serviceType){
        case 'Keyboard':
            return new KeyboardService();
        case 'Mouse':
            return new MouseService();
    }
    throw new Error("No implementation error");
}

//This should be an error
const mouseService = getService('Keyboard');


我正在傳遞鍵盤並期待 IKeyboardService。 目前,這是 getService 返回類型的錯誤。

你可以在這里玩: https://stackblitz.com/edit/typescript-leut1x

謝謝你。

您可以使用重載

function getService(serviceType: 'Keyboard'): KeyboardService;
function getService(serviceType: 'Mouse'): MouseService;
function getService(serviceType: keyof ServiceTypeMapping): ServiceTypeMapping[keyof ServiceTypeMapping] {
    switch(serviceType){
        case 'Keyboard':
            return new KeyboardService();
        case 'Mouse':
            return new MouseService();
        default:
            throw new Error("No implementation error");
    }
}

Typescript 游樂場

您還可以在返回時使用條件類型來執行此操作:

function getService<T extends ServiceType>(serviceType: T) {
    let returnService
    switch(serviceType){
        case 'Keyboard':
            returnService = new KeyboardService();
            break;
        case 'Mouse':
            returnService = new MouseService();
            break;
        default:
            throw new Error("No implementation error");
    }
    return returnService as T extends 'Keyboard' ? KeyboardService : MouseService
}

操場

暫無
暫無

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

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