6

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?

6
  • Human doesn't exist at runtime, are you talking about a type predicate? Commented Aug 22, 2021 at 9:49
  • You can use duck typing. Or since you've define a type for the object, then you can rely on TS since it will only allow objects that are assignable to A to be used as A. However, if you have an object of unknown shape, then you can only duck type it. Commented Aug 22, 2021 at 9:49
  • @VLAZ but how can I check that it doesn't have any unwanted properties (that aren't 'name' nor 'age' ? Commented Aug 22, 2021 at 10:07
  • Why would it matter? You can only access name and age through the Human interface anyway. Commented Aug 22, 2021 at 10:09
  • Check if there are any more keys? Although, in practice it rarely matters if there are more properties. If you get an object that also has an employeeId it doesn't mean it's not a human. Just a different type. Commented Aug 22, 2021 at 10:09

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

but how can I check that it doesn't have any unwanted properties (that aren't 'name' nor 'age' ?
that's duck typing for you. you need to make those assertion yourself. input instanceof ConcreteHumanClass and the like. you actually need to parse input. you can get all the keys of the object with Object.keys, and check for a match with what you expect. Up to you to decide how strict you want to be. In most all the cases, that's unnecessary to do tho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.