[Typescript] Excess Properties in Functions
interface User {
id: number;
name: string;
}
const users = [
{
name: 'Waqas',
},
{
name: 'Zain',
},
];
const usersWithIds: User[] = users.map((user, index) => ({
...user,
id: index,
// @ts-expect-error
age: 30,
}));
The above code doesn't emit any compiler error from Typescript, but the age
is not expected in User
type, we need to figure out a way to let Typescript to report error for it.
Solution:
interface User {
id: number;
name: string;
}
const users = [
{
name: 'Waqas',
},
{
name: 'Zain',
},
];
function transformUser(user: { name: string }, index: number): User {
return {
...user,
id: index,
// @ts-expect-error
age: 30,
};
}
const usersWithIds = users.map(transformUser);
Another way:
interface User {
id: number;
name: string;
}
const users = [
{
name: 'Waqas',
},
{
name: 'Zain',
},
];
const usersWithIds = users.map((user, index) => ({
...user,
id: index,
// @ts-expect-error
age: 30
} satisfies User));