简体   繁体   中英

How to check type parameter by typescript?

I want to make use of typescript type check in rpc call, but my rpc call is like this:

return await dataCaller.callWebService(apiId,req);

so with many rpc call, I have to define like this:

// get_by_product.ts
async function get_by_product(req:DataCenter.o2o.shipment_fare.get_by_product.Request):Promise<DataCenter.o2o.shipment_fare.get_by_product.Response>{
return await dataCaller.callWebService("o2o.shipment_fare.get_by_product",req);
}

// check_by_order.ts
async function check_by_order(req:DataCenter.o2o.shipment_fare.check_by_order.Request):Promise<DataCenter.o2o.shipment_fare.check_by_order.Response>{
return await dataCaller.callWebService("o2o.shipment_fare.check_by_order",req);
}

// check_by_cart.ts
async function check_by_cart(req:DataCenter.o2o.shipment_fare.check_by_cart.Request):Promise<DataCenter.o2o.shipment_fare.check_by_cart.Response>{
return await dataCaller.callWebService("o2o.shipment_fare.check_by_cart",req);
}

then I can call get_by_product with type check, how can I get type check without define so many function?

You can use union types :

function strOrNum(a: number): string | number {
    if(a > 0) {
        return a;
    }
    return "Negative";
}

also in generics:

interface IObj<T> {
    value: T;
}

function strOrNum(a: number): IObj<string | number> {
    if(a > 0) {
        return { value: a };
    }
    return { value: "Negative" };
}

And in your case:

async function get_by_product(req:DataCenter.o2o.shipment_fare.get_by_product.Request): Promise<DataCenter.o2o.shipment_fare.get_by_product.Response | DataCenter.o2o.shipment_fare.check_by_order.Response | DataCenter.o2o.shipment_fare.check_by_cart.Response> {
    return await dataCaller.callWebService("o2o.shipment_fare.get_by_product",req);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM