我想定义一个Object文字的类型,使用关键的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'
}
};
答案 0 :(得分: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 = {
...
}
在我看来,这使得代码更具可读性(与声明类型的内联方式相比)