TypeScript Traits
A lightweight, strictly typed utility for class composition (Traits/Mixins) in TypeScript. It allows you to combine a Base Class with multiple Trait Classes.
Requirements
- Typescript version 4.9 or higher
Installation
npm install github:daniloivk/ts-traits
Example usage
/**
* Class with common properties if any
*/
class Model {
constructor(public readonly id: number, public readonly name: string) {}
}
/**
* Class to apply traits to
*/
class RoleModel extends Model {
constructor(public readonly id: number, public readonly name: string) {
super(id, name);
}
}
/**
* Traits
*
* - Can declare properties and/or function
*/
class Comparable extends Model {
public is(other: this): boolean {
return this.id === other.id;
}
}
class Stringable extends Model {
public toString(): string {
return (this as any).name;
}
}
/**
* Class with traits applied
*/
const Role = withTraits(RoleModel, Comparable, Stringable);
/**
* New class instances
*/
const adminRole = new Role(1, 'Admin');
const userRole = new Role(2, 'User');
/**
* Trait functionalities usage
*/
console.table(adminRole);
console.table(userRole);
console.info(
`${adminRole} === ${userRole} ?`,
adminRole.is(userRole) ? 'true' : 'false'
);