DEV Community

Discussion on: Enum in typescript

Collapse
 
seangwright profile image
Sean G. Wright

How about creating a "Value Object" (often used in DDD).

class Terrain {
    public static readonly Meadow = new Terrain('meadow');
    public static readonly Ocean = new Terrain('ocean');
    public static readonly Forest = new Terrain('forest');
    public static readonly Unknown = new Terrain('unknown');

    public static readonly All = [
        Terrain.Meadow, 
        Terrain.Ocean, 
        Terrain.Forest
    ];

    private name: string;

    get Name() {
        return this.name;
    };

    protected constructor(name: string) {
        this.name = name;
    }

    find(name: string): Terrain | undefined {
        return Terrain.All.find(t => t.name === name);
    }

    isValid(name: string): boolean {
        return Terrain.All.some(t => t.name === name);
    }

    toString() {
        return this.name;
    }
}
Collapse
 
moseskarunia profile image
Moses Karunia

Hello, thanks for your answer. By the way I never heard of DDD yet. Care to elaborate? :)

Collapse
 
seangwright profile image
Sean G. Wright • Edited

Here's a link to the definition of Domain Driven Design (DDD)

"Domain-driven design is predicated on the following goals:

  • placing the project's primary focus on the core domain and domain logic;
  • basing complex designs on a model of the domain;
  • initiating a creative collaboration between technical and domain experts to iteratively refine a conceptual model that addresses particular domain problems."

And here's an implementation of Value Objects in Typescript