When using an adapter in the given example, I encountered a type error specifically on the last line of the getGloryOfAnimal
method. Despite having clearly defined types, I am puzzled by this issue.
interface ICheetah {
pace: string;
}
interface ILion {
mane: string;
}
let LionAdapter = {
endpoint: 'lion',
castRawData: (d: any) => d as ILion,
getValue: (d: ILion) => d.mane
}
let CheetahAdapter = {
endpoint: 'cheetah',
castRawData: (d: any) => d as ICheetah,
getValue: (d: ICheetah) => d.pace
}
type AnimalAdapter = typeof CheetahAdapter | typeof LionAdapter;
function getDataFromEndpoint(endpoint: string): any {
// receiving data from the server
// for simplicity's sake, synchronous here
if (endpoint === 'cheetah') {
return {
pace: 'lightning speed'
};
} else {
return {
mane: 'shiny mane'
};
}
}
function getGloryOfAnimal(adapter: AnimalAdapter): string {
let data = adapter.castRawData(getDataFromEndpoint(adapter.endpoint));
// encounter type error stating: 'cannot invoke expression whose type lacks a call signature'
return adapter.getValue(data);
}
console.log(getGloryOfAnimal(LionAdapter));
Instead of creating a union type ((T | U)
), I thought about defining an interface for the two adapters individually. However, the resulting interface would be exceedingly large in my case.
What are your thoughts? Do you think I should proceed with creating a single extensive common interface for the adapters?