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

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

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 Denunciar

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 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