2

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!

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
  • 2
    As far as I know this can't be done, because the values of the array can change to anything at **run time**, so there is no way to tell at **compile time** what values in it will be. Meaning: you can't mix value information with type information. – Krisztián Balla Aug 15 '21 at 08:07

2 Answers2

3

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"
}
Subrato Pattanaik
  • 5,331
  • 6
  • 21
  • 52
1

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.

amdev
  • 6,703
  • 6
  • 42
  • 64
  • Isn't this just a different implementation of what the questioner is trying to avoid? – Krisztián Balla Aug 15 '21 at 08:10
  • it's my suggestion of implementing it in a cleaner way at least. by doing this, the other developers would always think that there is a actions list that the actions of what ever module that they are working are is only limited to the values that are in the enum. I think this is the cleaner and simpler way to implement – amdev Aug 15 '21 at 08:14