Teneff
Teneff

Reputation: 32158

Is there a way to create dynamic union type with possible values returned from typeof

I thought since I can use as a regular function typeof(variable) I should be able to define a type

type TypeOf = ReturType<typeof typeof>

but tsc is complaining

Cannot find name 'typeof'.(2304)
Exported type alias 'TypeOf' has or is using private name 'typeof'.(4081)

TS Playground

Upvotes: 0

Views: 64

Answers (1)

Tobias S.
Tobias S.

Reputation: 23835

typeof is not a function, but rather a built-in operator in JavaScript. If you want to have a union of all possible return types of typeof, just use this pre-defined one:

type TypeOfReturn = 
 | "undefined" 
 | "object" 
 | "boolean" 
 | "number" 
 | "string" 
 | "symbol" 
 | "function" 
 | "object"

You could also use a wrapper function to infer the type.

function _typeof(arg: any) {
  return typeof(arg)
}

type TypeOfReturn = ReturnType<typeof _typeof>

Upvotes: 1

Related Questions