Consider the enum and type declarations in the code below:
enum MyEnum {
FIRST,
SECOND
};
type MyType = {
firstKey: string | null,
secondKey: boolean,
thirdKey: MyEnum
}
Next, a variable is declared using the type as follows:
let globalObject: MyType = {
firstKey: "String",
secondKey: false,
thirdKey: MyEnum.FIRST
}
Based on the solution provided in a different post, a generic type is created:
type MainFormDataField<T extends MyType> = {
[K in keyof T]: {
sKey: K;
vValue: T[K];
};
}[keyof T];
A function is intended to use this type to assign values to specific keys of an object without direct modification. The function should execute certain logic before and after changing any value in the object. However, when passing an array of objects to the function, the type of the value property behaves differently inside the function compared to outside.
function setSomeValue(elements?: MyFieldType<MyType>[]) {
if(!elements) {
// Alternative logic
return;
}
// Logic before value changes
for (const element of elements) {
globalObject[element.key] = element.value; // Type 'string | boolean | MyEnum | null' is not assignable to type 'never'. Type 'null' is not assignable to type 'never'.
}
// Logic after value changes
}
setSomeValue([{key: "secondKey", value: false}, {key:"thirdKey", value: false}]) // Type 'false' is not assignable to type 'MyEnum'.
The challenge is to resolve this issue. How can it be done?