Typescript: declare return type to be dependent on argument value? -
i have following function call:
this.get('barcode').scan();
is possible define function in way return type determined value of function argument. in case 'get' returns barcode class if called 'barcode' , mqtt class if called 'mqtt'.
yes, can use overload on strings this. example:
interface barcodescanner { scan(): number; } interface accelerometer { getacceleration(): number; } class myclass { get(name: 'accelerometer'): accelerometer; get(name: 'barcode'): barcodescanner; get(name: string): any; // fallback string signature get(name: string): { // implementation signature, not visible /* ... */ return undefined; } something() { let x = this.get('barcode'); x.scan(); // ok let y = this.get('accelerometer'); y.getacceleration(); // ok } }
Comments
Post a Comment