GithubHelp home page GithubHelp logo

lmfinney / ts-enums Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rauschma/enumify

40.0 4.0 3.0 225 KB

A fork of enumify that enables Java-like enums in TypeScript.

License: MIT License

JavaScript 6.06% TypeScript 93.94%
typescript enums

ts-enums's Introduction

Ts-Enums

A TypeScript library for enums, inspired by Java enums and forked from Enumify.

Motivation

Dr. Axel Rauschmeyer created Enumify to bring an analogue of Java's Enums to JavaScript. In a blog post, he explained why a naive implementation of enums in JavaScript lacks the power of Java Enums.

TypeScript Enums provide a start to a Java-style Enum implementation, but they lack the killer feature of Java's Enum: classes. Java's Enums are full classes, enabling properties and methods (including abstract methods and overriding within an enum). In contrast, TypeScript enums are limited to being namespaced integers or strings.

Enumify is a strong introduction to class-style enums in JavaScript, and this project ports the idea to TypeScript. This port loses the feature from Enumify of creating an enumeration from an array of Strings, but string-based TypeScript enums were added in 2.4.1, so that is not a large loss.

The basics

Install:

npm install ts-enums

Use:

import {Enum, EnumValue} from 'ts-enums';

export class Color extends EnumValue {
  constructor(name: string) {
    super(name);
  }
}

class ColorEnumType extends Enum<Color> {

  RED: Color = new Color('RED name');
  GREEN: Color = new Color('GREEN name');
  BLUE: Color = new Color('BLUE name');

  constructor() {
    super();
    this.initEnum('Color');
  }
}

export const ColorEnum: ColorEnumType = new ColorEnumType();

// examples of use
console.log(ColorEnum.RED.toString()); // Color.RED
console.log(ColorEnum.GREEN instanceof Color); // true

new Color();
    // Error: EnumValue classes can’t be instantiated individually

Unfortunately, this is not as terse as Enumify's syntax. Here are the steps:

  1. We define the implementation of EnumValue that defines each of the instances.
  2. We implement each instance of the EnumValue as a property on the Enum. Within the Enum, we call initEnum() with a unique name to set up all of the Enum-specific behavior.
  3. We export an instance of the enum so that other modules can use it.

Properties of Enum classes

Enum exposes the getter values, which produces an Array with all enum values:

for (const c of ColorEnum.values) {
    console.log(c.toString());
}
// Output:
// Color.RED
// Color.GREEN
// Color.BLUE

Enum exposes the methods byPropName and byDescription, to extract the EnumValue instance by either the property name of the object in the Enum or the description string passed into the EnumValue's constructor, respectively:

console.log(ColorEnum.byPropName('RED') === ColorEnum.RED); // true
console.log(ColorEnum.byDescription('RED name') === ColorEnum.RED); // true
true

Properties of enum values

Ts-Enums adds two properties to every enum value:

  • propName: the property name of the object in the Enum.

    > ColorEnum.BLUE.name
    'BLUE'
    
  • ordinal: the position of the enum value within the Array values.

    > ColorEnum.BLUE.ordinal
    2
    

Adding properties to enum values

The EnumValues are full TypeScript classes, enabling you to add properties and methods (see the tests for more examples).

import {Enum, EnumValue} from 'ts-enums';
import {Color, ColorEnum} from 'color';
 
class BridgeSuit extends EnumValue {
  constructor(name: string, private _isMajor: boolean = false) {
    super(name);
  }
 
  // can use simple properties (defensively-copied 
  // to maintain immutability)
  get isMajor(): boolean{
    return this._isMajor;
  }
 
  // can also use methods, though this isn't an ideal implementation. 
  // (I would probably used another property instead of an if-else)
  get color(): Color {
    if (this === BridgeSuiteEnum.SPADES 
        || this === BridgeSuiteEnum.CLUBS) {
      return ColorEnum.BLACK;
    } else {
      return ColorEnum.RED;
    }
  }
}
 
class BridgeSuitEnumType extends Enum {
  SPADES: BridgeSuit = new BridgeSuit('Spades', true);
  HEARTS: BridgeSuit = new BridgeSuit('Hearts', true);
  DIAMONDS: BridgeSuit = new BridgeSuit('Diamonds');
  CLUBS: BridgeSuit = new BridgeSuit('Clubs');
 
  constructor() {
    super();
    this.initEnum('BridgeSuit');
  }
 
  // can also have methods on the overall type
  get majors(): BridgeSuit[] {
    return this.values.filter((suit: BridgeSuit ) => suit.isMajor);
  }
}
 
const BridgeSuitEnum: BridgeSuitEnumType = 
  new BridgeSuitEnumType();
 
console.log(BridgeSuitEnum.HEARTS.color.toString()); // Color.RED
console.log(BridgeSuitEnum.HEARTS.isMajor); // true
// ```

## More information

* The directory [test/](test) contains examples.
* See [ngrx-example-app-enums](https://github.com/LMFinney/ngrx-example-app-enums) for a more complicated implementation supporting an [@ngrx](https://github.com/ngrx/store) app.

ts-enums's People

Contributors

johnjbarton avatar lmfinney avatar pbakondy avatar rauschma avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ts-enums's Issues

Ordinal order isn't guaranteed

Unless I'm mistaken, it looks like you are relying on getOwnPropertyNames to determine the order of the enum values from which you set the ordinal. I'm pretty sure the order of that array is not guaranteed by the spec and it's possible to get different orderings on different platforms. This could be disastrous if you were using the ordinal on both a web-browser and a server and expecting them to match.

I didn't dig into the code, but the original Enumify library took the list of value names as an array in the initEnum function. Perhaps you should do something similar and require the programmer to pass in the values of the enum as an array in the order in which they should be defined. Then the ordinal only changes if the programmer changes it.

At a minimum, you might want to note in your documentation that the ordinal isn't guaranteed between platforms (or who knows, maybe even between separate invocations on the same platform).

How to make a generic?

@Enum("text")
export class PeriodUnit extends EnumType<PeriodUnit>() {

    static readonly DAY = new PeriodUnit('d');

    private constructor(
        readonly text: string,
    ) {
        super()
    }
}
export function EnumProp<T extends IStaticEnum<T> & { text: string }>(
    enumCls: T,
    options?: PropOptions
) {
    return (target, propertyKey) => {
        Prop({
            ...(options as object),
            type: String,
            set: (v: T) => v.text,
            get: (v: string) => enumCls.valueOf(v)
        })(target, propertyKey);
    }
}
@Schema()
export class Period {

    @Prop({ required: true })
    value: number

    @EnumProp(PeriodUnit,{
        required: true
    })
    unit: PeriodUnit
}

Argument of type 'typeof PeriodUnit' is not assignable to parameter of type 'IStaticEnum<typeof PeriodUnit> & { text: string; }'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.