I'm beginner in TS, so sorry for stupid question)))
I need to know if type is includes variable value
For example I have type Action = "accept" | "decline"
and I need to know the result of testing by this type.
Like if (Action.includes("skip")) saySkip()
Of course I know that I could create new arr with needed values but in my case I need to know if global type HTMLElementTagNameMap
includes my value)
CodePudding user response:
It's possible, but only on the TypeScript side - since you're only concerned with the types, and types do not exist in emitted code, all you'll have to work with will be the resulting type. Eg
interface HTMLElementTagNameMap {
"a": HTMLAnchorElement;
"abbr": HTMLElement;
"address": HTMLElement;
// ...
}
type DoesNotExist = 'foobar';
type exists = DoesNotExist extends keyof HTMLElementTagNameMap ? true : false;
will give you an exists
type of false
.
But this isn't particularly useful, since it's still just a type. Whatever you're trying to do, you may need to create emitted JavaScript code instead.
// use a regular expression to transform HTMLElementTagNameMap into the below
const mapValues = [
"a",
"abbr",
"address",
// ...
];