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

297
Visualizações
How to get default values from Typescript object?

lets say I have

 type DataItems = {
  id: number;
  title: string;
  subItems?: Array<DataItemChild>;
  checked: boolean;
  isEdit:boolean;
};

I defined an object as

const myObj = {} as DataItems;

when I inspect myObj I see {}.

I was expectiong:

   {
      id: 0,
      title: '',
      subItems:[],
      checked: false,
      isEdit:false
    }

I could define my objest as :

  const myObj = {
    id : 0,
    title: '',
    subItems: [],
    checked: false,
    isEdit: false,
  } as DataItems;

But I wonder is there a way to get this as default without manually needing to define it?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The simplest way to do that is to make a class, but you always need to use new DataItems to "get" the default values.

type DataItemChild = any;

class DataItems {
  id: number = 0;
  title: string = '';
  subItems: DataItemChild[] = []
  checked: boolean = false;
  isEdit:boolean = false;
};

const myObj = new DataItems();
console.dir(myObj);

TypeScript Playground

about 4 years ago · Juan Pablo Isaza Relatório

0

No, there is no way in typescript which gives you default value without initializing it. How would typescript know that you want to initialize number from 0, string should be empty, boolean should be empty and so on. You can do the following:

type DataItems = {
  id: number;
  title: string;
  subItems?: Array<DataItemChild>;
  checked: boolean;
  isEdit:boolean;
};

const myObj : DataItems = {
      id: 0,
      title: '',
      subItems:[],
      checked: false,
      isEdit:false
    };

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