I would like to combine two objects in TypeScript and include only the keys that exist in the first object
Below are my code.
type User = {
username: string
passcode: number;
}
const userA: User = {
username: 'A',
passcode: 1234
}
const updateValues = {
username: 'B',
unexpectedKey: "I shouldn't be here. But I exsits in users' post request"
}
// Update userA
for (const key in updateValues) {
if (key in userA) {
// We know that `key` has the type `keyof User` now
userA[key] = updateValues[key]
}
}
But TypeScript reports the following errors.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User'.
No index signature with a parameter of type 'string' was found on type 'User'.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ username: string; unexpectedKey: string; }'.
No index signature with a parameter of type 'string' was found on type '{ username: string; unexpectedKey: string; }'.
How can I fix these errors with type assertion?