You can't do that; a constructor can't return null. See What values can a constructor return to avoid returning this?.
What you can do is create a factory method that will return null
. See below. Your question shows you ignoring the argument if it's provided but I assumed you'd want to use it, so I made that change. See below.
class SampleClass {
constructor(someArg){
this.someArg = someArg;
}
static create(someArg) {
return (someArg) ? new SampleClass(someArg) : null;
}
}
const willBeNull = SampleClass.create();
console.log(willBeNull);
const willNotBeNull = SampleClass.create("foo");
console.log(willNotBeNull);
You can also throw an error, as some commenters suggested:
class SampleClass {
constructor(someArg){
if (!someArg) throw new TypeError("an argument is required");
this.someArg = someArg;
}
}
const sampleClass = new SampleClass("foo");
console.log(sampleClass);
try {
const willError = new SampleClass();
// below console.log will not be reached
console.log(willError);
} catch(e) {
// instead we will catch the error here
console.log(e.stack);
}