lal rishav
lal rishav

Reputation: 569

check if an object have all the property of a class in typescript

I have a class abc in typescript

export class ABC{
    public a : any;
    public b : any;
    public c? : any;
    public d? : any;
}

Now in my function I receive an input lets say data:any Now i want to check if that input i.e data have all the required property of class ABC. Is there any option to do this without using hasOwnProperty on every key of class ABC and object data.

Upvotes: 1

Views: 2584

Answers (2)

hackape
hackape

Reputation: 19947

TL;DR. Using hasOwnProperty is very likely inevitable, unless you’re absolutely sure about your function usage, input data source to your function is totally under control.

Longer version:

You must understand the difference of static type check and runtime check. TS is a static type checker, but it doesn’t have a runtime. Code in TS is transpiled to JS before execution, and run in a JS runtime engine.

The only way TS can check whether properties of data meet the requirement, is that piece of information must first exist within the type system. But in your case data: any has swallowed all meaningful type information, leaving TS nothing to work on.

Even if data’s type is more concrete, something like data: { a: any; b: any; } etc. TS can only check that, in your code base, you didn’t explicitly write any code that pass in invalid arguments.

If somewhere you write validate(anyData), where anyData: any, then the safe guard is gone. Plus, it cannot guarantee in JS runtime, invalid arguments are never passed in.

Upvotes: 0

user2258152
user2258152

Reputation: 675

Instantiate the class to get all properties and use the every function to check if all keys are indeed in the passing object.

function hasAllProperties (data, YourClass) {
  const yourClass = new YourClass()
  return Object.keys(yourClass).every((key) => data[key] !== undefined)
}

Usage

hasAllProperties(data, ABC)

Upvotes: 2

Related Questions