Typescript: how to get a list of values acceptable/defined by interface?

Viewed 1058

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?

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

interface LocalState {
  justifyContent: typeof contentPositions[number];
}

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

Related