[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 ageis 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));

 

posted @ 2024-08-01 14:46  Zhentiw  阅读(9)  评论(0编辑  收藏  举报