-1

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
shank087
  • 492
  • 8
  • 17

2 Answers2

2

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";
Garuno
  • 1,935
  • 1
  • 9
  • 20
  • @Garuno - Thank you...If I have too many keys (may be 10-15), is this the only way to have it autopopulate? – shank087 Nov 28 '22 at 08:12
  • If you want to have autocomplete, you will have to define exactly what keys with what types are allowed/required in the object. – Garuno Nov 28 '22 at 08:15
2

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