class-traits
v1.0.1
Published
A small utility package to apply PHP-style traits to JavaScript classes.
Downloads
9
Readme
Class Traits
A small utility package to apply PHP-style traits to JavaScript classes.
Usage
Traits can be defined as below.
class SwimTrait {
canSwim() {
return true;
}
}
class MammalTrait {
declare public isMale: boolean;
producesMilk() {
return !this.isMale;
}
}
Applying the traits:
import { UseTraits } from "class-traits";
@UseTraits(SwimTrait)
class Fish {}
interface Fish extends SwimTrait {}
@UseTraits(SwimTrait, MammalTrait)
class Dolphin {
public constructor(public readonly isMale: boolean) {}
}
interface Dolphin extends SwimTrait, DolphinTrait {}
assert(new Fish().canSwim());
assert(new Dolphin(true).canSwim());
assert(new Dolphin(false).producesMilk());
Note how an extra interface declaration is needed in order for the TypeScript interpreter to recognize the type augmentation.