Reputation: 5613
I have an interface called Obj
and it contains a bunch of boolean
interface Obj {
isVisited: boolean,
isChecked: boolean,
isToggled: boolean
}
And I want to initialize an object of this type and assign every property of it with false
const obj: Obj = {
isVisited: false,
isChecked: false,
isToggled: false
}
I wonder is there a programmatic way of doing it rather than manually tying it out?
Upvotes: 2
Views: 3978
Reputation: 16127
You can create a class which implement Obj
interface with default value for the properties.
class ObjClass implements Obj {
isVisited: boolean = false;
isChecked: boolean = false;
isToggled: boolean = false;
}
const obj = new ObjClass();
Now, obj
has 3 attributes and default values are false
.
Or, try keep it simple, you can create a factory
function to create default object.
function genObjDefault(): Obj {
return {
isVisited: false,
isChecked: false,
isToggled: false
}
}
const obj = genObjDefault();
Upvotes: 2
Reputation: 370619
I'd go the other way around: instantiate an object, then take the type from the object:
const obj = {
isVisited: false,
isChecked: false,
isToggled: false
}
type Obj = typeof obj;
Upvotes: 1
Reputation: 579
As far as I know you cannot have a default initialization for interfaces, but you can create a class with default values like below.
class TestA {
private label = "";
protected value = 0;
public list: string[] = null;
}
Emitted javascript would be
var TestA = /** @class */ (function () {
function TestA() {
this.label = "";
this.value = 0;
this.list = null;
}
return TestA;
}());
Upvotes: 0