Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda