【问题标题】:Typescript: define type of an objectTypescript:定义对象的类型
【发布时间】:2016-12-02 11:43:39
【问题描述】:

我想使用键值对来定义 Object 字面量的类型,如下所示。无论如何都无法做到这一点。请帮忙。

export const endPoints: {name: string: {method: string; url: string;}} = {
  allFeed: {
    method: 'GET',
    url: 'https://www.yammer.com/api/v1/messages.json'
  },
  topFeed: {
    method: 'GET',
    url: 'https://www.yammer.com/api/v1/messages/algo.json'
  },
  followingFeed: {
    method: 'GET',
    url: 'https://www.yammer.com/api/v1/messages/following.json'
  },
  defaultFeed: {
    method: 'GET',
    url: 'https://www.yammer.com/api/v1/messages.json/my_feed.json'
  }
};

【问题讨论】:

    标签: object types typescript


    【解决方案1】:

    你很亲密,应该是:

    const endPoints: { [name: string]: { method: string; url: string; } } = {
        allFeed: {
            method: 'GET',
            url: 'https://www.yammer.com/api/v1/messages.json'
        },
        ...
    };
    

    你也可以使用接口:

    interface EndPoint {
        method: string;
        url: string;
    }
    
    interface EndPointMap {
        [name: string]: EndPoint;
    }
    
    const endPoints: EndPointMap = {
        ...
    }
    

    或类型:

    type EndPoint = {
        method: string;
        url: string;
    }
    
    type EndPointMap = {
        [name: string]: EndPoint;
    }
    
    const endPoints: EndPointMap = {
        ...
    }
    

    在我看来,这使代码更具可读性(与声明类型的内联方式相比)

    【讨论】:

    • 非常感谢。 :-)
    猜你喜欢
    • 2022-01-17
    • 2020-04-14
    • 2023-03-08
    • 2018-05-29
    • 2015-02-05
    • 2021-12-08
    • 2019-12-21
    • 2021-01-29
    • 2022-01-25
    相关资源
    最近更新 更多