0

So I have this typescript class with an interface implemented in the constructor parameter:

    interface responseObject {
      a: string;
      b: boolean;
      c?: boolean; 
   }

   class x
   {
     a: string;
     b: boolean;
     c: boolean; 
     constructor(args: responseObject) {
       //check if non optional parameters are not supplied
       if(!args.a || !args.b) throw new Error("Error"); 
       //Trying to initialize class data member -> not working
       this.a = args.a;
       this.b = args.b;
     }
   }

Now I have two questions, my first one is how can I access the different parameters supplied inside args, for example how could I check if they are both supplied (something that looks like the thing I tried !args.a or !args.b) and my second question is how can I supply a default value for c if it is not supplied?

Thanks in advance.

1 Answer 1

1

You could do that.

constructor({ a, b, c = 'defaultValue' }) {
    //check if non optional parameters are not supplied
    if(!a || !b) throw new Error("Error"); 
}

Note that you have to explicitly throw the error, there is no short syntax for that.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your response, however would that be possible using an interface and also declaring c as optional?
An interface has no JavaScript representation so it's unable to do runtime checking
Oh ok @Guerric P , and if I want c to be optional should I include ? or not because there is already a default value?
ok, thank you! also last question, if I let's say want to access interface properties how would I do that, like is there something I could use like args.a?
|

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.