[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 logAll
function param.
So far, as we can see the type of func
is (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));
};