繁体   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