When using TypeScript 4.5.4, an error message
Type 'any' is not assignable to type 'never'.(2322)
is being thrown for versions 1, 2, 3, and 4 of the code snippet provided below or accessible in the TypeScript playground). Interestingly, no error is reported for versions 5 and 6. Removing either the num
or str
property eliminates all errors.
Can someone provide insight into this behavior?
const myObj = {
num: -1,
arr: [1, 2, 3],
str: '',
};
const proxy = new Proxy(myObj, {
set(target, prop: keyof typeof myObj, value) {
/* none of these works */
// Ver. 1
if (prop in target) target[prop] = value;
// Ver. 2
target[prop] = value;
// Ver. 3
target[prop as keyof typeof myObj] = value;
// Ver. 4
switch (prop) {
case 'num':
case 'str':
target[prop] = value;
break;
}
/* while these works */
// Ver. 5
switch (prop) {
case 'num':
target[prop] = value;
break;
case 'str':
target[prop] = value;
break;
}
// Ver. 6
switch (prop) {
case 'num':
target[prop] = value;
break;
default:
target[prop] = value;
break;
}
return true;
},
});
console.log('proxy : ', proxy);