Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda