developeen
developeen

Reputation: 61

How can I check if object is of custom type in typescript?

I looked everywhere and couldn't find any way to check if a given object is of some custom type or not. For example, I declare type Human as such:

type A = { name: string; age: number; }

Then I want to have a function that will receive an object and decided whether it's of type Human or not. Something like:

isOfTypeHuman = (input) => typeof input === Human

I have a feeling it's impossible, but I thought maybe I'm missing something. Any ideas?

Upvotes: 6

Views: 11029

Answers (1)

Federkun
Federkun

Reputation: 36924

Types do not exists at runtime. They are a only useful at compile-time, and stripped away afterwards.

You are required to check yourself:

// if it quacks like a duck..
isOfTypeHuman = (input) => input.name !== undefined && input.age !== undefined

You can additionally use user-defined type guard to make the rest of the code aware that that's a Human

isOfTypeHuman = (input: any): input is Human => input.name !== undefined && input.age !== undefined

Upvotes: 4

Related Questions