2

Array:

const myStrings = ["one", "two", "three"];
const newString = "two";

newString will simply be of type string, but I want the type to be something like element of myStrings.

How can I do this if the values in the array may or may not change?

4
  • I think you want type literals but it's not clear. What does something like element of myStrings mean? Commented Apr 7, 2022 at 9:35
  • newString would be a string that exists in myStrings Commented Apr 7, 2022 at 9:37
  • 1
    Well, ALL VOTES are subjective. "This question does not show any research effort; it is unclear or not useful". This seems to tick (as a minimum) two of those boxes. ¯\_(ツ)_/¯ Commented Apr 7, 2022 at 9:55
  • I think you should use enum for that Commented Apr 16, 2022 at 8:17

1 Answer 1

1

You can use typeof myStrings[number], but only if myStrings has as const telling TypeScript that its contents don't change:

const myStrings = ["one", "two", "three"] as const;
type MyStringsElement = typeof myStrings[number]; // For convenience
const newString: MyStringsElement = "two";

Playground example

With the myStrings contents you've shown, the type of newString will be "one" | "two" | "three". That's a union of three string literal types, meaning that the only valid values for newString are "one", "two', or "three" (as compile-time constant values).

(Note: typeof myStrings[number] is evaluated by TypeScript as (typeof myStrings)[number], which may be surprising. I used to think I needed the parentheses, and I'm not sure it's not best to have them for clarity even if they aren't needed... :-) )

Sign up to request clarification or add additional context in comments.

Comments

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.