Problem - TS Playground
I'm trying to dynamically assign a number to an object based on its shape.
export async function assignNumber<
T extends Record<string, number>,
K extends keyof T,
>(
object: T,
key: K,
) {
object[key] = 42; // ❌ error Type 'number' is not assignable to type 'T[K]'
}
Error
Type 'number' is not assignable to type 'T[K]'.
'number' is assignable to the constraint of type 'T[K]', but 'T[K]' could be instantiated with a different subtype of constraint 'number'.(2322)
Minimal Reproducible Example - TS Playground
After reading this great answer explaining in detail the error "could be instantiated with a different subtype of constraint", I came up with this:
function hello<T extends string>(msg: T) {
msg = 'world' // ❌ Type 'string' is not assignable to type 'T'
}
const hi: 'hi' = 'hi'
// ✅ No error as type 'hi' is a subtype of string.
// ❌ But shouldn't be assign anything else than 'hi'
hello(hi)
Error
Type 'string' is not assignable to type 'T'.
'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string'.(2322)
Solution ? - TS Playground
export async function assignNumber<
T extends Record<string, number>,
K extends keyof T,
>(
object: T,
key: K
) {
object[key] = 42 as T[K]; // Solution = `as T[K]` ❓
}
Is it a TypeScript limitation due to a loose interpretation of type contstraints in generics ?
In otherwords, because subtypes also satisfy the constraint an error may occur ? ("could be instantiated with a different subtype of constraint")
How would you manage this error ?
Thank you very much for your help