Home > Back-end >  How does typescript check primitive type at runtime?
How does typescript check primitive type at runtime?

Time:09-02

I know Typescript stripes away any type or interface at compile time. so how is it possible to check the object's primitive type using typeof keyword then? Guess custom interface vs primitive types are dealt in a different way?

const a = "string";
const b = 123;
const c = {};
const d = undefined

console.log(typeof a) -> 'string'
console.log(typeof b) -> 'number'
console.log(typeof c) -> 'Object'
console.log(typeof d) -> 'undefined'

CodePudding user response:

typeof is actually a JS operator.

Typescript uses the power of runtime JS operators like typeof to do things like narrowing at compile time.

For exemple :

declare const foo: string | number | Function | boolean

function bar() {
    switch (typeof (foo)) {
        case "string":
            return foo.toLowerCase()
        case "number":
            return foo.toExponential()
        case "boolean":
            return foo
        default:
            return foo()
    }
}

Playground

CodePudding user response:

TS doesn't do any runtime checks.

What you're probably confusing here is that typeof is actually a JS operator.

  • Related