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!

1
  • 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. Commented Aug 15, 2021 at 8:07

2 Answers 2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

Isn't this just a different implementation of what the questioner is trying to avoid?
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

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.