Search code examples
typescriptoopabstract-class

How to use abstract class in typescript?


In the following code, I'm getting an error on implementing the abstract method getPrice.

abstract class Exchange {
    public coins=[];
    abstract getPrice();
}
class Binance extends Exchange {
    getPrice(coin,stable_coin){
       return  axios.get(`https://api.binance.com/api/v3/avgPrice?symbol=${coin.symbol}${stable_coin.symbol}`).then(res=>res.data.price)
    }
}
class Bittrex extends Exchange {
    getPrice(coin,stable_coin){
        return  axios.get(`https://api.bittrex.com/api/v1.1/public/getticker?market=${stable_coin.symbol}-${coin.symbol}`).then(res=>res.data.result.Last);
     }
}

I'm getting the following error:

Property 'getPrice' in type 'Binance' is not assignable to the same property in base type 'Exchange'. Type '(coin: any, stable_coin: any) => any' is not assignable to type '() => any'.ts(2416)


Solution

  • You need to match the parameters of the abstract method as well. your derived classes are passing arguments that arent defined in the base class.

    abstract class Exchange {
        public coins=[];
        abstract getPrice(coin:any, stable_coin: any): any;
    }
    class Binance extends Exchange {
        getPrice(coin: any, stable_coin: any): any {
           return  axios.get(`https://api.binance.com/api/v3/avgPrice?symbol=${coin.symbol}${stable_coin.symbol}`).then(res=>res.data.price)
        }
    }
    class Bittrex extends Exchange {
        getPrice(coin: any, stable_coin: any): any {
            return  axios.get(`https://api.bittrex.com/api/v1.1/public/getticker?market=${stable_coin.symbol}-${coin.symbol}`).then(res=>res.data.result.Last);
         }
    }