0

I am updating an open-source typescript module that allows you to work with all of the common vendors. I need to have an array vendors that has all of the vendors as the Vendor type. Is there a way to have the same effect from the code, but not have to repeat all of the vendors twice?

type Vendor =
  | "ah"
  | "apple"
  | "atsc"
  | "epub"
  | "hp"
  | "khtml"
  | "moz"
  | "ms"
  | "o"
  | "rim"
  | "ro"
  | "tc"
  | "wap"
  | "webkit"
  | "xv";

const vendors: Vendor[] = [
  "ah",
  "apple",
  "atsc",
  "epub",
  "hp",
  "khtml",
  "moz",
  "ms",
  "o",
  "rim",
  "ro",
  "tc",
  "wap",
  "webkit",
  "xv",
];

Please don't tell me to just add the string[] type to the vendors array because I need to use the Vendor type in other places within the code.

Thanks for your help and sorry that I am a typescript noob ;)

sno2
  • 3,274
  • 11
  • 37
  • @VLAZ yes, but there probably isn't a way to set `vendors` to the type of `Vendor[]`, right? – sno2 Sep 17 '20 at 21:58
  • Ok, I'll just set the type of `vendors` to `string[]` and do typechecks whenever I use it. – sno2 Sep 17 '20 at 22:02
  • 1
    And should that matter? `Vendor` is already an alias to `"ah" | "apple" | "atsc"` etc. The type of `vendors` would be *exactly* that. You can always just declare it as `const vendorsArr = [ "ah", "apple", "atsc", /* ... */ ] as const;` and then do `type Vendor = typeof vendorsArr[number];` followed by `const vendors: Vendor[] = vendorsArr` or something along those lines. – VLAZ Sep 17 '20 at 22:04
  • lol yea I just thought of that. Thanks for your help! – sno2 Sep 17 '20 at 22:05

0 Answers0