There is an interface defined as:
export default interface Cacheable {
}
and then another one that extends it:
import Cacheable from "./cacheable.js";
export default interface Coin extends Cacheable{
id: string; // bitcoin
symbol: string; // btc
name: string; // Bitcoin
}
Next, there's a Cache object with a method called getData
structured like this:
public async getData<T extends Cacheable>(key: string): Promise<T | T[]> {
This allows retrieving cached coin data using the following code snippet:
const coins = (await cache.getData('coins.json')) as Coin[];
The concern arises when the generic getData
method can still be used with types that do not extend Cacheable
. For example, TypeScript compiles the following successfully despite expectations:
const num: number = (await cache.getData('coins.json')) as number
The question remains, why is there no restriction to only use types that are Cacheable
with the generic getData
method?