Arpan Das
Arpan Das

Reputation: 172

How to get the type definition name of an object?

If the code is something like this below,

    interface foo {
        one: number;
        two: string;
    }

const bar: foo = { one: 5, two: "hello" };

Then how can I get the type definition of constant 'bar' ? With

console.log(typeof bar);

I am getting 'Object' but not the exact definition name.

Thanks in advance.

Upvotes: 1

Views: 91

Answers (1)

Fenton
Fenton

Reputation: 250842

Interfaces, types, and ambient declarations are all removed during compilation. This is the concept of "type erasure" that you'll find in the TypeScript docs.

If you need types to continue to exist, you'll need to use constructs that remain after compilation. For example:

class Foo {
    constructor(public one: number, public two: string) { }
}

const foo = new Foo(5, 'hello');

console.log(foo.constructor.name);

There is a pattern in TypeScript called a Discriminated Union that might be what you are looking for if you need to differentiate types - in most other cases, this kind of information should be used with caution.

Upvotes: 1

Related Questions