There are numerous scenarios where this can be applied.
For instance, in a situation where the object is already defined as an object literal, and there is no need to explicitly define its type but you still want to pass it around in a type-safe manner to methods:
let rectangle1 = { width: 100, height: 200 };
type Rectangle = typeof rectangle1;
function clone (r: Rectangle ): Rectangle {
return r;
}
Alternatively, when a variable or function is exported by a module but is not publicly exposed, using typeof
allows for creating a named type for the variable. For example, it was utilized in this answer
import * as ts from 'typescript' // Import will be elided as long as we only use types from it, so we don't have the compiler code loaded at runtime
type CompilerOptions = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ?
TResult extends { options: infer TOptions } ? TOptions : never : never;
type TypeAcquisition = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ?
TResult extends { typeAcquisition?: infer TTypeAcquisition } ? TTypeAcquisition : never : never;
typeof
can also be used without a named type. For instance, defining the type of a parameter to be the same as another parameter's type helps avoid redundant typing, especially for lengthy types.
function asPromise(value: string| number| Date) : Promise<typeof value> { return null as any; }
The possibilities are endless, these are just a few examples.