Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a TypeScript type as all possible resulting values from typeof?

Tags:

typescript

I am looking to define a type as all of the possible resulting values from using the typeof operator on something.

Essentially, I am looking for a quicker way to do this, without any sort of intermediate function or variable.

function getTypeOf(value: any) {
  return typeof value;
}

type T0 = ReturnType<typeof getTypeOf>; // "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

How can I get TypeScript to generate the same T0 type ("string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function") without an intermediate function or variable whose existence is only to help generate this type?

Note: this does not have much practical application at the moment, I'm just curious if this is possible.

like image 476
Velocirooster Avatar asked Sep 20 '25 07:09

Velocirooster


1 Answers

This works and is a bit shorter than yours:

const uselessVariable = typeof (1 as any);

// type Test = "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
type Test = typeof uselessVariable;

Unfortunately it seems there is no way to do this without creating a useless intermediate variable; something like type Test = typeof typeof (1 as any) would be simpler but it's not allowed:

TypeScript intentionally limits the sorts of expressions you can use typeof on.

Specifically, it’s only legal to use typeof on identifiers (i.e. variable names) or their properties.

So it's a syntax error to use typeof in a type context unless it's followed by an identifier. That means it really is necessary to declare an identifier (in Javascript-land) in order to construct the type you want programmatically.

Playground Link

like image 73
kaya3 Avatar answered Sep 23 '25 00:09

kaya3