【问题标题】:Typescript function extended interface typeTypescript 函数扩展接口类型
【发布时间】:2021-08-07 07:55:03
【问题描述】:

我有一个函数,它接受一个没有 id 属性的对象数组,并返回所有添加了 id 属性的对象。

const pickIdAndDocs = (arr) => {
  return arr.map(doc => ({
    id: 1,
    ...doc
  }))
}

现在,例如,如果我有这个界面

interface iUser {
  name: string;
}

和一个包含 iUser

类型值的数组
let users: iUser[] = [ {name: "John"}, {name: "Joe"} ];

我如何指定函数pickIdAndDocs的返回类型,以便它返回一个数组,其中每个项目都是它所采用的输入类型的扩展类型,并添加了 id 属性

function pickIdAndDocs<T>(items : T[] ) : extendedT[];

这个函数可以接受任何类型的数组(总是对象/键值对),返回所有带有附加 id 属性的项目。

还是我以错误的方式接近这个?谢谢:)

【问题讨论】:

    标签: typescript generics typescript-generics typescript-types


    【解决方案1】:

    本质上,我们想通过组合两种类型来构建新类型。一个带有{id: number},另一个是传递给函数的任何内容。这正是intersection type 所做的。假设我对您的问题的解释是正确的,我认为这就是您想要的:

    interface User {
      name: string;
    }
    
    type WithId<T> = T & { id: number };
    
    const pickIdAndDocs = <T,>(arr: T[]): WithId<T>[] => {
      return arr.map((doc) => ({
        id: 1,
        ...doc,
      }));
    };
    
    let users: User[] = [{ name: "John" }, { name: "Joe" }];
    
    const usersWithId = pickIdAndDocs(users);
    
    // No warning!
    usersWithId[0].id;
    usersWithId[0].name;
    
    // Warning: Property 'age' does not exist on type 'WithId<User>'.
    usersWithId[0].age;
    

    这里是 TS Playground 链接:https://tsplay.dev/ND5B4m

    【讨论】:

    猜你喜欢
    • 2015-04-01
    • 2022-12-06
    • 2018-04-09
    • 2018-06-20
    • 1970-01-01
    • 2020-05-04
    • 2021-08-07
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多