【问题标题】:How do I declare a type for array object using 'Pick' and '&' keyword at the same time in TypeScript如何在 TypeScript 中同时使用“Pick”和“&”关键字声明数组对象的类型
【发布时间】:2022-01-26 22:22:26
【问题描述】:

我对 TypeScript 很陌生,我想要的是为数组对象声明一个类型,如下所示。

const temp = [{
  id: 0, // number
  follower_id: 0, // number
  followee_id: 0, // number
  created_at: '', // string 
  delete_at: '', // string
}, {
  id: 1,
  follower_id: 1,
  followee_id: 0,
  created_at: '',
  delete_at: '',
}];

我可以为临时数组创建一个新类型,但我只想重用我之前定义的类型,这样我就可以避免重复无意义的输入。 所以,这是我制作的类型。 userStateType 的两个接口。

interface IUserInfo {
  id: number;
  created_at: string;
  deleted_at: string | null;
  username: string;
  description: string;
  image_url: string;
  name: string;
  updated_at: string;
}

interface IFollows {
  follower_id: number,
  followee_id: number
}

我试着像下面这样写下我的 UserStateType。

type UserStateType = {
  userInfo: IUserInfo | null
  followers: Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows | null
};

但 UserStateType 中的追随者必须是数组类型而不是对象类型,因此会发生类型错误。 (目前,我使用这种类型来避免类型错误。followers: [] | null

我什至不能使用[],因为我不仅使用了Pick关键字,还使用了&amp;

在这种情况下,我该如何想出有效的解决方案?

如果我的解释不够清楚,请评论!

【问题讨论】:

  • 删除 pick 标签 - 注意它的用途,与 TS 无关。
  • @TonyG 好的。我删除了那个标签。谢谢你的想法。 :)

标签: typescript typeerror


【解决方案1】:

非常很接近。你只需要把它变成一个数组:

followers: (Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows)[] | null

或者你可以创建一个Follower 类型并使用它:

type Follower = Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows;

type UserStateType = {
  userInfo: IUserInfo | null;
  followers: Follower[] | null;
};

【讨论】:

    【解决方案2】:

    你只是缺少括号:

    interface IUserInfo {
        id: number;
        created_at: string;
        deleted_at: string | null;
        username: string;
        description: string;
        image_url: string;
        name: string;
        updated_at: string;
    }
    
    interface IFollows {
        follower_id: number,
        followee_id: number
    }
    
    type UserStateType = {
        userInfo: IUserInfo | null
        followers: (Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows)[]
    };
    

    然后你可以这样做:

    const example:UserStateType = { followers:{created_at:'',deleted_at:'',followee_id:0,follower_id:0}], userInfo:null}
    

    【讨论】:

    • 天啊!我不知道我在这里添加了[]!非常感谢!
    猜你喜欢
    • 2021-11-06
    • 2021-07-16
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2021-07-27
    • 2020-12-05
    相关资源
    最近更新 更多