Query:
Why doesn't a compile-time error occur when I overlook adding nested fields to an object of type T
, while constructing the object using object spread?
Illustration:
interface User {
userId: number;
profile: {
username: string
}
}
function updateUsername(user: User): User {
return {
...user,
profile: {
// Error (expected)
}
}
}
function updateUsernameGeneric<T extends User>(user: T): T {
return {
...user,
profile: {
// No error (unexpected... why?)
}
}
}
My personal theory regarding this issue:
I speculate that TypeScript allows subtypes to delete properties of their super types, which might explain why for some subtype T
of User
, the profile
property could potentially have no properties. (If true, it's news to me that TypeScript permits this behavior...)
TypeScript Version 4.1.2