I have a question regarding my application, where I am utilizing values that can either be static or functions returning those values.
For TypeScript, I have defined the static values along with their types in the following manner:
type Static = {
key1: number;
key2: string;
};
Subsequently, I created a type for the dynamic values by using keyof Static
:
type DynamicValue<T> = () => T;
type Dynamic = {[key in keyof Static]: DynamicValue<Static[key]>;};
This approach should yield the same result as explicitly writing out the dynamic type like this:
type DynamicValue<T> = () => T;
type Dynamic = {
key1: DynamicValue<number>;
key2: DynamicValue<string>;
};
(Both methods resulted in the same error within the code snippet below)
Currently, I have a function designed to take dynamic values and convert them into static values. However, an issue arises during this process:
function dynamicToStatic(d: Dynamic): Static {
const o: Static = {key1: 0, key2: ''};
for (const [key, callback] of Object.entries(d))
// The assignment on the left-hand side triggers an error:
// "Type 'string | number' is not assignable to type 'never'."
o[key as keyof Static] = callback();
return o;
}
(There's also another version of the function intended to accept a Partial<Dynamic>
as input and produce a Partial<Static>
, which presents a similar error message: "Type 'string | number' is not assignable to type 'undefined'.")
The error seems unrelated to Object.keys
, as even this modified version resulted in the same error:
function dynamicToStatic(d: Dynamic): Static {
const o: Static = {key1: 1, key2: ''};
const keys = ['key1', 'key2'] as Array<keyof Static>;
for (const key of keys)
o[key] = d[key]();
return o;
}
To suppress the error, I could replace the problematic line with:
(o as any)[key as keyof Static] = callback();
However, TypeScript seems to imply that there is a potential issue, leaving me puzzled about what exactly might be wrong here.
So, why am I encountering this error in the provided code? What do the types 'undefined' / 'never' signify in the context of the error message?