To inform TypeScript that a property will be part of the object, utilize a type assertion:
interface MyObject {
prop1: string;
prop2: string;
prop3: string;
prop4: string;
prop5: string;
}
let initialValues: MyObject;
//Setting a property
initialValues = {
prop1: 'xxxx'
prop2: 'yyyy'
}
//Assigning values to existing properties
[3,4,5,6].map(i => {
initialValues[`prop${i}` as keyof MyObject] = 'zzzz';
});
TypeScript Playground
However, exercise caution with this approach! TypeScript does not verify if the property is valid, leading to potential loss of runtime type safety. TypeScript remains silent in such cases.
If you are aware of the possible array values, specifying them will enable TypeScript to recognize valid keys:
interface MyObject {
prop1: string;
prop2: string;
prop3?: string;
prop4?: string;
prop5?: string;
}
let initialValues: MyObject;
//Setting a property
initialValues = {
prop1: 'xxxx',
prop2: 'yyyy'
};
//Assigning values to existing properties
let values: (3 | 4 | 5 | 6)[] = [3, 4, 5, 6];
values.map(i => {
initialValues[`prop${i}`] = 'zzzz';
});
TypeScript Playground
In this scenario, TypeScript only flags prop6
for invalidity. Opt for this method whenever feasible to maintain type safety.