簡體   English   中英

TypeScript通用方法檢查接口並進行強制轉換

[英]TypeScript Generic method check Interface and cast

我想基於對象類型使用differents通用方法。 這是我的代碼示例:

export interface IStorable {
    Enable : boolean;
}

async GetItemStored<T extends IStorable>(toExecute : () => Promise<T>){//Some Code}

async GetItem<T>(toExecute : () => Promise<T>){//Some Code}


Main<T>(toExecute : () => Promise<T>){
    if(this.IsStorable(toExecute)){
        await this.GetItemStored(this.CastInStorable(toExecute));
    } else {
        await this.GetItem(toExecute);
    }
}

IsStorable<T>(() => Promise<T>) :boolean {
    // ???
}

CastInStorable<T, U extends IStorable >(() => Promise<T>) : () => Promise<U> {
    // ???
}

你能幫我寫兩個函數IsStorable和CastInStorable

提前致謝

除非您在創建時以某種方式標記了promise,否則除非知道結果,否則無法知道結果類型:

IsStorable(value: any) : value is IStorable  {
    return (value as any).Enable !== undefined;
}
async Main<T>(toExecute : () => Promise<T>){
    let result = await toExecute();
    if(this.IsStorable(result)){
        // result will be ISortable beacuse IsStorable si a type guard
        let asSortable = result;
        await this.GetItemStored(()=> Promise.resolve(asSortable));
    } else {
        await this.GetItem(()=> Promise.resolve(result));
    }
}

編輯

標記toExecute函數的另一種方法如下所示:

type SortablePromiseGenerator<T> = { () : Promise<T & IStorable>; isSortable: true };
type NonSortablegenerator<T> = () => Promise<T & {Enable? : never }>;

....
IsStorable<T>(toExecute: SortablePromiseGenerator<T> | NonSortablegenerator<T>) : toExecute is SortablePromiseGenerator<T> {
    return (toExecute as SortablePromiseGenerator<T>).isSortable;
}

sortableGenerator<T extends IStorable>(toExecute : ()=> Promise<T>) : SortablePromiseGenerator<T>{
    let toExecuteResult = toExecute as SortablePromiseGenerator<T>;
    toExecuteResult.isSortable  = true;
    return toExecuteResult
}
sample (){
    this.Main(()=> Promise.resolve({})) // call with anything
    this.Main(this.sortableGenerator(()=> Promise.resolve({}))) // will fail at compile if result is not sortable

    // Ok call 
    this.Main(this.sortableGenerator(()=> Promise.resolve({
        Enable : true
    })));

    // Will fail at compile time, if the result conforms to the ISortable interface it must be wraped with sortable
    this.Main(()=> Promise.resolve({
        Enable : true
    })) // 
}

暫無
暫無

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

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