打字稿:定义对象的类型 [英] Typescript: define type of an object

查看:53
本文介绍了打字稿:定义对象的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

你很亲近,应该是:

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

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

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

这篇关于打字稿:定义对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆