menu
Channels
Team

[Solved] Is there a way to create type from an array?

January 26, 2019 at 3:24pm

[Solved] Is there a way to create type from an array?

January 26, 2019 at 3:24pm (Edited 9 months ago)
I have a file domElements.ts , which contains a list of DOM element names.
export default [
"a",
"abbr",
...
"button",
...
];
TypeScript documentation, String Literal Types(https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types) lets one to specify allowable values.
type Easing = "ease-in" | "ease-out" | "ease-in-out";
Is there a way to create such a type using values from an array imported from domElement.ts?
Here is my attempt to create a type
import domElements from "../domElements";
export type DOMType = domElements;
// export type Target = string | ComponentType<any>;
export type Target = DOMType | ComponentType<any>;

Error message

Image

January 26, 2019 at 4:01pm
Also tried following but domElement could not be found even though it can be used in code above without complaints 🤔
  • reply
  • like

January 26, 2019 at 10:49pm
🤔 Able to pass domElements but printDOMType accepts xxx which is not in domElements array...
  • reply
  • like
  • reply
  • like
Hard-coding a list of domElements by hand seems to work (https://codesandbox.io/s/30y547yl91) but...
Edited
  • reply
  • like
  • reply
  • like
Passing the array as a variable, domElements infers the typeof arr[number] as string (https://codesandbox.io/s/qrrq24k7q) 🤔
Edited
  • reply
  • like
I guess it's not so easy to do so yet... https://stackoverflow.com/a/54061487/4035
  • reply
  • like
Took long enough to realize that 😛
  • reply
  • like
Maybe I should just copy & paste the list of array values for now in the interface declaration
Edited
  • reply
  • like

January 30, 2019 at 4:59pm
I've finally got it working with a dictionary.
  • reply
  • like
domMap.ts
export default {
a: "a",
abbr: "abbr",
address: "address",
area: "area",
...
}
Edited
  • reply
  • like
Type declaration
  • reply
  • like
import domMap from "./domMap";
type DOMType = keyof typeof domMap;
  • reply
  • like
  • reply
  • like
DOMType now accepts only DOM elements
  • reply
  • like
Edited
  • reply
  • like
Perhaps I should make domMap values as empty string to decrease bundle size 🤔
  • reply
  • like

February 2, 2019 at 7:13pm