简体   繁体   中英

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?

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

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM