Type-position typeof
Concept and syntax
In a type position typeof value obtains the static type of an existing value binding. This differs from runtime typeof, which returns a JavaScript string describing the value category. Use type-position typeof to reuse inferred object or function types without repeating their declarations.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
const defaults={count:2,label:"tea"};const other:typeof defaults={count:7,label:"coffee"};console.log(other.count,typeof other);Expected output:
7 objectCommon mistake
Intentionally invalid; compile separately and do not execute.
const defaults={count:2,label:"tea"};const other:typeof defaults={count:"7",label:"coffee"};Expected diagnostic: TS2322. The inferred count property is numeric. Match the static type.
Practice and recap
Use typeof on a function declaration and assign a compatible function.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type-position typeof — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
const defaults={count:2,label:"tea"};const other:typeof defaults={count:7,label:"coffee"};console.log(other.count,typeof other);Which diagnostic and explanation match the rejected example under the lesson settings?
const defaults={count:2,label:"tea"};const other:typeof defaults={count:"7",label:"coffee"};