[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));
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-08-06 [Machine Learning] Evaluation Metrics
2020-08-06 [CSS] Create Basic Effects with CSS box-shadow
2020-08-06 [Javascript] Natively Format JavaScript Dates and Times
2019-08-06 [Functional Programming] liftA2 and converge
2019-08-06 [Javascript] Convert a forEach method to generator
2019-08-06 [Flutter] Platform Checking
2019-08-06 [Flutter] Stateless widget and Stateful widget