2

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?

1
  • you could declare it as a class and assign properties in constructor Commented Sep 2, 2020 at 3:07

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

0

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

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.