Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript type from string values from an object

The object with values as array of strings:

const STUFF = {
  abc: ["string_1", "string_2"],
  def: ["string_3", "string_4"],
  xyz: ["string_1", "string_2", "string_4"],
}

how to define a type that allows only values from these arrays?

type StuffStr = "string_1" | "string_2" | "string_3" | "string_4";
like image 715
Alex Avatar asked Jun 20 '26 00:06

Alex


1 Answers

If you use a const assertion on STUFF, it becomes a matter of indexing typeof STUFF.

const STUFF = {
  abc: ["string_1", "string_2"],
  def: ["string_3", "string_4"],
  xyz: ["string_1", "string_2", "string_4"],
} as const;

type StuffStr = typeof STUFF[keyof typeof STUFF][number];
// type StuffStr = "string_1" | "string_2" | "string_3" | "string_4"

Playground

like image 97
iz_ Avatar answered Jun 22 '26 12:06

iz_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!