Home > database >  How to declare a Typescript variable that is going to be set just once but later
How to declare a Typescript variable that is going to be set just once but later

Time:12-13

With const the value should be set at the time of declaration, with let the variable could be changed, I need a Typescript (or javascript) variable that is undefined until is set, and once set, it cannot be changed.

CodePudding user response:

This isn't possible with a single primitive value, but the logic is easy to implement in JavaScript plus type safety by having a setter method that checks whether the value has already been set, and a getter method to retrieve it.

const obj = (() => {
  let val: number;
  return {
    setVal: (newVal: number) => {
      if (val !== undefined) {
        throw new Error('Value has already been set');
      }
      val = newVal;
    },
    getVal: () => {
      if (val === undefined) {
        throw new Error('Value has not been set yet');
      }
      return val;
    }
  };
})();

// will throw an error
const result1 = obj.getVal();

// will return 3
obj.setVal(3);
const result2 = obj.getVal();

// will throw an error if run just after the above
obj.setVal(5);

CodePudding user response:

as I understand you might need something like this, you cannot use const with this, only let and you need to set the initial type otherwise it will inference any by default or you can uses union type like string| number so you could later on set it to both of those types.

let value : string;      // string | number
value = 'newValue as string' 

  • Related