Mateusz Czarczyński
Mateusz Czarczyński

Reputation: 21

TypeScript property with allowed values taken from an array at runtime

The thing I'm struggling with is the way to specify the allowed values for a property in TypeScript.

I have this interface that has the said property statically typed:

interface SomeInterface{
    prop: "bell" | "edit" | "log-out"
}

But I would need something like this:

const list = ["bell", "edit", "log-out"]

interface SomeInterface{
    prop: list(allowed are all values from list)
}

Here the list of allowed values is changing dynamically.

FYI it is my first time asking on stackoverflow. Thanks!

Upvotes: 2

Views: 287

Answers (2)

Subrato Pattanaik
Subrato Pattanaik

Reputation: 6049

You can read more about const from this answer or from the official documentation.

const list = ["bell", "edit", "log-out"] as const;
interface SomeInterface{
    prop: (typeof list)[number] // the type would be union of array values
   //  here it would "bell" | "edit" | "log-out"
}

Upvotes: 3

amdev
amdev

Reputation: 7452

You need enum here

Enums are the predefined values, that you can specify for values and they are strict and can't typescript will give you an error when you put values more than defined items in your enum.

in your case you can do like below:

enum MY_ACTION_LIST {
  BELL = 'bell',
  EDIT = 'edit',
  LOG_OUT = 'log-out'
}

interface SomeInterface {
  props: MY_ACTION_LIST
}

by doing this, you will assure that the props could not be anything else other than items you had specified in your enum.

More info here.

Upvotes: 2

Related Questions