0

I have enum that looks like this

export enum Alignment {
  Top = 'top',
  Right = 'right',
  Bottom = 'bottom',
  Left = 'left',
}

Commonly I will use it in defining interface for e.g. react component props like

interface CompProps {
  align: Alignment;
}

But now wonder if I can use only the part of this enum, like

interface CompProps {
  align: `part of Alignment: left and top`;
}

Is there a common pattern for this?

I may think of:

A. align: Alignment.Left | Alignment.Top;

B. creating new enum for this task like

enum CompAlignment {
  Top = Alignment.Top,
  Left = Alignment.Left,
}
1
  • 3
    I think you answered your own question align: Alignment.Left | Alignment.Top; should work best. Commented Apr 24, 2018 at 13:57

1 Answer 1

1

According to typescript docs:

When all members in an enum have literal enum values, some special semantics come to play.

The first is that enum members also become types as well! For example, we can say that certain members can only have the value of an enum member.

This means option A is valid as you can leverage union enums to achieve what you are looking for.

enum ShapeKind {
    Circle,
    Square,
}

interface Circle {
    kind: ShapeKind.Circle;
    radius: number;
}

interface Square {
    kind: ShapeKind.Square;
    sideLength: number;
}

let c: Circle = {
    kind: ShapeKind.Square,
    //    ~~~~~~~~~~~~~~~~ Error!
    radius: 100,
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.