DEV Community

Discussion on: The Type of a `type` in Typescript

 
maxheiber profile image
Max Heiber

I rushed and used the wrong terminology in my last reply, sorry about that.

Here is type-level typeof, I promise it is a thing and is distinct from value-level/JS typeof. Type-level typeof returns a type. JS typeof returns a string.

const three = 3;

// all uses of `typeof` below are in type position.
// this is not the same as JS `typeof`
type Three = typeof three;
const x: typeof three = 3;
declare function foo(param: typeof three): void;

typescriptlang.org/play/?ssl=9&ssc...

Thread Thread
 
stereobooster profile image
stereobooster

Indeed you are right

type Three = typeof three;

if typeof is in type position this is TS thing. I never paid attention to this

Thread Thread
 
maxheiber profile image
Max Heiber

cool, huh!

It sneaks under the radar, since, as far as I can tell, there is no documentation on it.

Thread Thread
 
stereobooster profile image
stereobooster • Edited

But the error is the same as if you try to use type in place of value

type Test = 1
const x = typeof Test;
// the same as 
console.log(Test);
 // 'Test' only refers to a type, but is being used as a value here.(2693)

So it seems like type checker itself doesn't differentiate TS and JS versions of typeof and always returns error for JS version.