Object 类型脚本:定义对象的类型

Object 类型脚本:定义对象的类型,object,types,typescript,Object,Types,Typescript,我想用键valye对定义对象文字的类型,如下所示。无论如何,我都无法做到这一点。请帮忙 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

我想用键valye对定义对象文字的类型,如下所示。无论如何,我都无法做到这一点。请帮忙

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

你很接近,应该是:

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 = {
    ...
}

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

非常感谢。:-)