Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
TypeScript: class property optional but not undefined

Is there any way that you can have a property on a Class that is optional, but won't be undefined?

Note in the example below, the Class constructor takes a type of itself (that's intentional)

class Test {
  foo: number;
  bar: string;
  baz?: string;

  constructor(test: Test) {
    this.foo = test.foo;
    this.bar = test.bar
    this.baz = test.baz || "Default";
  }
}

const first = new Test({foo: 1, bar: "Bob"});

const str = "Some Default String about Bob";

str.replace(first.baz, "New Value");
// Type 'undefined' is not assignable to type 'string | RegExp'.(

I know I can use the ! operator, but would prefer not to

str.replace(first.baz!, "New Value");

Seems maybe this question addresses it the answer — "class properties can't rely on default values"

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As far as I can tell, you don't want the class property to be optional you want the constructor parameter to be optional. Which is easy enough to do:

interface TestParams {
  foo: number;
  bar: string;
  baz?: string; // optional
}

class Test {
  foo: number;
  bar: string;
  baz: string; // NOTE: not optional!

  constructor ({
    foo,
    bar,
    baz,
  }: TestParams) {
    this.foo = foo;
    this.bar = bar;
    this.baz = baz ?? "Default";
  }
}

Note that I used the nullish coalescing operator rather than logical "or" so that if baz is undefined we'll assign the default but if it's an empty sting it won't be overwritten. If you are really concerned about the duplication, and you don't mind having your constructor take positional parameters rather than an object you can condense it back down quite a bit:

class Test2 {
  constructor (
    public foo: number,
    public bar: string,
    public baz = "Default",
  ) {}
}

The behavior isn't quite the same regarding the optional param, but it's pretty close.

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!