Joji
Joji

Reputation: 5613

TypeScript: how do I initialize an object and give some default values from its type

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

Answers (3)

hoangdv
hoangdv

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

CertainPerformance
CertainPerformance

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

Purushothaman
Purushothaman

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

Related Questions