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));
};
标签:Functions,Typescript,obj,string,Object,func,const,id,name From: https://www.cnblogs.com/Answer1215/p/18345891