Typescript: define type of an object

一笑奈何 提交于 2020-05-15 10:35:07

问题


I want to define the type of an Object literal, with key valye pairs, like below. In any way can't manage this. Please help.

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'
  }
};

回答1:


You're very close, should be:

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

You can also use interfaces:

interface EndPoint {
    method: string;
    url: string;
}

interface EndPointMap {
    [name: string]: EndPoint;
}

const endPoints: EndPointMap = {
    ...
}

Or types:

type EndPoint = {
    method: string;
    url: string;
}

type EndPointMap = {
    [name: string]: EndPoint;
}

const endPoints: EndPointMap = {
    ...
}

Which makes the code more readable in my opinion (when compared to the inline way of declaring the type)



来源:https://stackoverflow.com/questions/38630316/typescript-define-type-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!