1.0.1 • Published 11 months ago

class-traits v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
11 months ago

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.

1.0.1

11 months ago

1.0.0

11 months ago