Home > other >  TypeScript types for JS objects
TypeScript types for JS objects

Time:11-28

I am struggling to have VS code suggest the list of keys for the below snippet. Could you please help me to get the keys autopopulate?

const myVar : Record<string, string> = {
        key1: 'val1',
        
     }
    myVar.key2 = "val2",
    myVar.key3 = "val3";

     myVar. //doesn't populate the keys

CodePudding user response:

In general, typescript does not track mutations. Except this case. Apart from that, once you defined explicit type for myVar, I mean Record<...>, TS will not infer any properties for you, except the case when you use satisfies operator.

However, if you want to use explicit type Record<string, string> for your myVar and want to mutate it, you can consider using assertion functions

const myVar: Record<string, string> = {
  key1: 'val1',

}
myVar.key2 = "val2",
myVar.key3 = "val3";

function mutate<
  Obj extends { [prop: string]: string },
  Key extends string,
  Value extends string
>(obj: Obj, key: Key, value: Value): asserts obj is Obj & Record<Key, Value> {
  Object.assign(obj, { [key]: value })
}

mutate(myVar, 'key1', 'val2')

myVar.key1 // val2

Playground

I strongly recommend you to avoid mutations in typescript. TS does not like it, see my article

CodePudding user response:

You need to actually specify the keys that are possible in your object. As the documentation says, Record is not the right type for you:

Record<Keys, Type>

Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.

You can do something like this:

interface MyInterface {
  key1: string;
  key2: string;
  key3: string;
}

const myVar : MyInterface = {
    key1: 'val1',
    key2: '',
    key3: '',
 }
 myVar.key2 = "val2":
 myVar.key3 = "val3";
  • Related