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