Home > Back-end >  How to define an empty object in typescript
How to define an empty object in typescript

Time:12-16

Background

Stuck with typescript. I understand this declarations:

let varName:number; //null,string,..declare simple variables.  
let arrName:string[] // or arrName:number[]. etc 

Apparently this is used for objects:

//knowing type of the property
let obj: {property:string, also:number[]} = {property:'hello', also:[1,2,3]}

//now knowing the type of the property
let obj: {property:any, also:any[]} = {property: a && b || c, also:[1,'string', 'etc']}

But what happens when we don't know the names of the properties in advance?

Particularly, I am trying to translate this JS bit:

let myObj = {}
myObj[prop] = value

but we don't know the names of the properties in advance.

CodePudding user response:

You have a few options:

  1. You can use an index signature type that allows any string or any number, for instance:

    let myObj: {[key: string]: number} = {};
    myObj[prop] = value;
    

    ...allows any string property name, with the values expected to be numbers. (Or you can use {[key: number]: number} to make the keys numbers. string and number are your only two index signature options.)

  2. You can use the Record utility type, for example Record<string, number> which does much the same thing as the above:

    let myObj: Record<string, number> = {};
    myObj[prop] = value;
    
  3. You can use a Map instead of an object:

    let myObj: Map<string, number> = new Map();
    myObj.set(prop, value);
    

In all three of those, number as the value type is just an example, it can be any type you want (including a union type), or unknown if you won't know the type, or any if you want to allow any type.

It may be obvious, but I'll say it anyway: This does mean TypeScript can't help you with using the wrong property name on the object. :-) But that's inevitable if the property name is a runtime thing.

  • Related