object - Typescript:定义对象的类型

标签 object types typescript

我想用键值对定义对象文字的类型,如下所示。无论如何都无法管理这个。请帮忙。

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):

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

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

关于object - Typescript:定义对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38630316/

相关文章:

javascript - 仅在选择所有选项时绑定(bind)数据

javascript - 避免使用 angular、HttpClient 和 Observables 的回调 hell

javascript - 概念 : Discern between Array, JavaScript 中的伪数组和对象

C语言,报数据类型错误

java - 如何将用户定义的数据类型中的值插入到java中的对象中?

javascript - 使用循环变量进行同名函数调用 - Javascript

javascript - 如何使用 const 关键字将 Javascript 常量创建为对象的属性?

java - registerNatives() 方法有什么作用?

javascript - 无法推送到数组对象

c++ - 确定传递给模板函数的变量类型