[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 @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示