[Typescript] Approaches for Typing Object Parameters

Consider this implementation of returnBothOfWhatIPassIn:

const returnBothOfWhatIPassIn = (params: { a: unknown; b: unknown }) => {
  return {
    first: params.a,
    second: params.b,
  };
};

This time the function takes in a params object that includes a and b.

 

import { expect, it } from 'vitest';
import { Equal, Expect } from '../helpers/type-utils';

const returnBothOfWhatIPassIn = <T1, T2>(params: { a: T1; b: T2 }) => {
  return {
    first: params.a,
    second: params.b,
  };
};

it('Should return an object where a -> first and b -> second', () => {
  const result = returnBothOfWhatIPassIn({
    a: 'a',
    b: 1,
  });

  expect(result).toEqual({
    first: 'a',
    second: 1,
  });

  type test1 = Expect<
    Equal<
      typeof result,
      {
        first: string;
        second: number;
      }
    >
  >;
});

 

So the solution 1, we use:

const returnBothOfWhatIPassIn = <T1, T2>(params: { a: T1; b: T2 }) => {
  return {
    first: params.a,
    second: params.b,
  };
};

 

Solution 2:

interface Params<T1, T2> {
  a: T1;
  b: T2;
}

const returnBothOfWhatIPassIn = <T1, T2>(params: Params<T1, T2>) => {
  return {
    first: params.a,
    second: params.b,
  };
};

 

posted @   Zhentiw  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-01-11 [Functional Programming] Transition State based on Existing State using the State ADT (liftState, composeK)
2019-01-11 [Apollo Server] Get started with Apollo Server
2017-01-11 [Git] Use git add --patch for better commit history and mitigating bugs
2017-01-11 [ES6] Use ES6 Proxies
2017-01-11 [Javascript] Javascript 'in' opreator
2016-01-11 [React Testing] The Redux Store - Multiple Actions
点击右上角即可分享
微信分享提示