2

How to get a list of values acceptable/defined by interface?

Example I have a local state defined as:

interface LocalState {
    justifyContent: 'space-between' | 'center' | 'flex-start' | 'flex-end' | 'space-around' | 'space-evenly';
}

And I want to get an array of items which will contain

['space-between', 'center', 'flex-start', 'flex-end', 'space-around', 'space-evenly']

Is it possible to extract this information from TS type-system?(Or does it get stripped out while transpiling to Javascript)

If it is possible how?

1
  • 1
    Interface has NO footprint in the generated JavaScript, so it doesn't fit for the intended purpose. Use a class instead. More on interfaces in the docs - typescriptlang.org/docs/handbook/interfaces.html Commented Jan 19, 2021 at 23:19

2 Answers 2

2
const contentPositions = <const>["space-between", "center", "flex-start", "flex-end", "space-around", "space-evenly"];

interface LocalState {
  justifyContent: typeof contentPositions[number];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since types/interfaces are a concept related to types, and JS is an extremely dynamically typed language... it wouldn't be a great idea. That being said, we can create an enum with all the required properties and simply use JS Object.values() to get an array from it. Of course, we can use the enum as a type.

enum LocalState {
    spaceBetween = 'space-between',
    center = 'center',
    flexStart = 'flex-start'
}

const localStateArr: LocalState[] = Object.values(LocalState);

console.log(localStateArr) // logs ["space-between", "center", "flex-start"]

Partial Example: Playground Link

This is how you can create a simple interface and use it.

interface LocalStateWithEnum {
    string : LocalState;
}

// or even more strict:

interface LocalStateWithEnumStrict {
    'justifyContent' :  LocalState;
}

const a: LocalStateWithEnumStrict = {
   justifyContent : LocalState.center
}

Full example: Playground Link

1 Comment

Using a string literal type ('space-between' | 'center' | ...) rather than enums would be a more straightforward approach. It's too easy to mistakenly use values vs keys in enums. Here's an interesting reading - Wonderland of TypeScript enums

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.