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.
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
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