Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Is there a union of string literal types for the output of typeof?

Tags:

typescript

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

like image 942
Boogiechillin Avatar asked Sep 05 '25 03:09

Boogiechillin


1 Answers

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:

  • creating a variable with type any
  • calling JS typeof on that variable, which will return the union of all possible types
  • creating a typescript type that uses TS typeof 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

like image 123
Linda Paiste Avatar answered Sep 08 '25 00:09

Linda Paiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!