Search code examples
typescript

Typeof of a string literal


When i declare a constant string, typescript gives it the literal type

const x = 'X' // x is of 'X' type

so i get the following error

let y: typeof x = 'Y' // error Type '"Y"' is not assignable to type '"X"'

but why when i check it in an if sentence or console.log it i get string?

if (typeof x === 'X') console.log('OK') // types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"X"' have no overlap
console.log(typeof x) // string

thanks


Solution

  • JavaScript’s runtime typeof operator is barely related to TypeScript’s type-level typeof operator.

    The former can be used on any value, and the TypeScript error message already told you what it can evaluate to – a string, at runtime:

    "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

    The latter can only be used on variables and properties, and evaluates to a type at typechecking time.

    Just think of them as two different operators with the same name, like how | is bitwise or in JavaScript and type union at the type level in TypeScript.

    As for actually achieving the effect of logging a TypeScript type, see Can I get TypeScript to reveal what type it has determined for an expression?