Imagine you have an object with properties that are of different types, and you need to assign a dynamic value to a property identified dynamically. While this is easily done in JavaScript, how can you accomplish the same in TypeScript without encountering the TS(2322) error 'not assignable to type 'never'', preferably without resorting to using 'any'?
Take a look at the sample code (playground here):
interface Film {
name : string;
durationInSeconds : number;
}
const myFunction = function(
film: Film,
filmPropertyName: keyof Film,
newValue: string | number
) {
let value = film[filmPropertyName];
console.log('Existing value:', value);
film[filmPropertyName] = newValue;
value = newValue;
if(typeof film[filmPropertyName] === typeof newValue) {
value = newValue;
film[filmPropertyName] = newValue;
}
if(typeof film[filmPropertyName] === 'string' && typeof newValue === 'string') {
value = newValue;
film[filmPropertyName] = newValue;
}
}
In a simple scenario like this, one might suggest changing all properties to the same type, but in real-world scenarios where multiple types are required, this solution falls short.
Switching the type of the 'film' parameter to 'any' may resolve the error but could lead to other issues when passing data to other functions within the scope.
While casting before assignment eliminates the error, it compromises TypeScript's typechecking power, and adding 'any' annotations goes against the TypeScript methodology. How should you handle this situation?