I'm currently leveraging Typescript Mixins in order to combine my class functionalities without repeating code (like the getImage function mentioned below).
After following the guidelines provided at https://www.typescriptlang.org/docs/handbook/mixins.html, I was able to successfully implement them.
However, I've encountered an issue that I'm struggling to resolve - I am no longer able to use my classes with mixins as a type (refer to the functions towards the bottom).
Any suggestions on how I can work around this challenge?
Thank you!
// A - Implementing Mixins
type Constructor<T = {}> = new (...args: any[]) => T;
function withStoredImages(Base: Constructor) {
return class extends Base {
storageToken?: string;
getImage(formatSlug: string) {
if (!this.storageToken) return null;
return `${formatSlug}${this.storageToken}.png`;
}
};
}
// B - Defining the primary class
class BaseEntity {
name: string;
constructor(name: string) {
this.name = name;
}
}
export const Entity = withStoredImages(BaseEntity);
const myEntity = new Entity('1', 'Bobby');
// Works
console.log(myEntity.storageToken);
// Works
console.log(myEntity.getImage('original'));
// Although we are able to use BaseEntity as a type for our argument
export function printBaseEntity(entity: BaseEntity) {
// Works
console.log(entity.name);
console.log(entity.storageToken); // Error: "Property 'storageToken' does not exist on type 'BaseEntity'."
}
export function printEntity(entity: Entity) {
console.log(entity.name);
}
export function printEntity2(entity: typeof Entity) {
console.log(entity.storageToken); // Error: "Property 'storageToken' does not exist on type 'typeof (Anonymous class)'?"
}
For live demonstration, please visit: https://stackblitz.com/edit/typescript-rbk3fn?file=entity.model.ts