Lets say I want to have a common type for dynamicly created objects, which always have a name property and some numerical properties. Now I would like to pass such an object around and access the numerical properties dynamically but guarded.
I was thinking of something like this:
type MyObject<T extends string = string> = {[P in T]:number;} & {name:string};
type MyProperty<T extends MyObject> = Exclude<keyof T, "name">;
function processValue<T extends MyObject>(enhanced:T, key:MyProperty<T>) {
enhanced[key]; // always a number
}
const o:MyObject<"speed" | "price"> = {name:"car", speed:100, price:200};
processValue(o, "speed");
however typescript throws compile error
Argument of type 'MyObject<"speed" | "price">' is not assignable to parameter of type 'MyObject<string>'.
Type 'MyObject<"speed" | "price">' is not assignable to type '{ [x: string]: number; }'.
Property 'name' is incompatible with index signature.
Type 'string' is not assignable to type 'number'.
Is there a way to modify MyObject
or MyProperty
so I can keep using processValue()
function as is?