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