2

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?

2
  • 1
    dont use as when possible. try const myObj: DateItems = {}. So will Typescript will throw an error that you are missing some props. To your question: not that im aware of. Commented Aug 11, 2021 at 19:14
  • Typescript is not for runtime Commented Aug 11, 2021 at 19:29

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

This is a way I guess. The thing that I am after if there is a typescript built-in feature that simply does this for me. Your solution is good but it still involves me writing this manually. same as const myObj = { id : 0, title: '', subItems: [], checked: false, isEdit: false, } as DataItems; and using it as a default type.
I will accept this since it is a solution, I think what I am after is something typescript does not support at this moment in time.
What you want does not exist in TypeScript or JavaScript. The benefit over setting them is you need to set them every time, manually. Also of note: using as just tells the compiler you know better - it does nothing at runtime nor any validation to confirm it "works".
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.