I'm aware that the output type of typeof is a string.
In typescript there's this pattern, called a "Union of string literal types":
export type Fruit = 'banana' | 'apple' | 'orange';
Q: Is there an importable union of string literal types that exists in any library allowing one to ensure a field can only be a possible output of the typeof operator?
Example psuedoish code:
import {JSType} from '@somelib/types'; // <--- what I want, this is a bogus type/lib
export class SomeClass {
data: any;
type: JSType;
constructor (params) {
this.data = params.data;
this.type = typeof params.data;
}
render = () => {
switch(this.type){
case 'boolean':
// return checkbox html component
// more type cases
default:
// return input html component
}
}
}
I could manually create the type I need, but I'd prefer to let someone smarter than me handle the maintenance of the type, and future proof if JS/TS ever adds some type besides 'string' | 'number' | 'function' | 'object' | 'undefined'.
Also, in a pinch if I need to add a custom type, then I can just extend the existing type, to include the strings I need.
Edit #1: Updated terminology. Thanks to jcalz
There has to be a better way to do this, seeing as those definitions already exist somewhere. But we can access the union in a very roundabout way by:
any
typeof
on that variable, which will return the union of all possible typestypeof
to access that union as a type.const x: any = "";
const t = typeof x;
type TypeofTypes = typeof t;
This creates
type TypeofTypes = "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
Typescript Playground Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With