[Typescript] Typing Functions with Object Params

import { expect, it, vitest } from 'vitest';

const logId = (obj: { id: string }) => {
  console.log(obj.id);
};
const logName = (obj: { name: string }) => {
  console.log(obj.name);
};

const loggers = [logId, logName];

const logAll = (obj) => {
  loggers.forEach((func) => func(obj));
};

it('should log id and name of an object', () => {
  const consoleSpy = vitest.spyOn(console, 'log');

  logAll({ id: '1', name: 'Waqas' });

  expect(consoleSpy).toHaveBeenCalledWith('1');
  expect(consoleSpy).toHaveBeenCalledWith('Waqas');
});

We need to type the logAllfunction param.

 

So far, as we can see the type of funcis (obj: {id: string} & {name: string})

 

I would expect the obj to be type as {id: string} | {name: string}, but Typescript doesn't work like that.

 

Solution: 

const logAll = (obj: { id: string; name: string }) => {
  loggers.forEach((func) => func(obj));
};

// or

const logAll = (obj: { id: string } & { name: string }) => {
  loggers.forEach((func) => func(obj));
};

 

posted @ 2024-08-06 19:56  Zhentiw  阅读(5)  评论(0编辑  收藏  举报