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

293
Views
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 answers
Answer question

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 Report

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