Reputation: 876
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.
Upvotes: 0
Views: 37
Reputation: 31805
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.
Upvotes: 1