[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 3 years 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

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 🤔January 26, 2019 at 10:49pm
🤔 Able to pass
domElements
but printDOMType
accepts xxx
which is not in domElements
array...Hard-coding a list of
domElements
by hand seems to work (https://codesandbox.io/s/30y547yl91) but...Passing the array as a variable,
domElements
infers the typeof arr[number]
as string
(https://codesandbox.io/s/qrrq24k7q) 🤔I guess it's not so easy to do so yet... https://stackoverflow.com/a/54061487/4035
Took long enough to realize that 😛
Maybe I should just copy & paste the list of array values for now in the interface declaration
January 30, 2019 at 4:59pm
domMap.ts
export default {a: "a",abbr: "abbr",address: "address",area: "area",...}
Type declaration
import domMap from "./domMap";type DOMType = keyof typeof domMap;
DOMType now accepts only DOM elements
Perhaps I should make
domMap
values as empty string to decrease bundle size 🤔February 2, 2019 at 7:13pm
To share with the world :)
https://www.slightedgecoder.com/2019/02/02/dynamically-build-typescript-string-literal-type/