-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
1

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

2 Comments

@Garuno - Thank you...If I have too many keys (may be 10-15), is this the only way to have it autopopulate?
If you want to have autocomplete, you will have to define exactly what keys with what types are allowed/required in the object.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.