我想从下面的 typescript 函数中返回这样的对象: marked = { '2024-08-21': { dots:[food,cycling] }, '2024-08-22': { ...
我想从下面的打字稿函数中返回这样的对象:
marked = {
'2024-08-21': {
dots:[food, recycling]
},
'2024-08-22': {
dots:[food, recycling]
}
}
这是我目前所拥有的。
function addKeysAndValuesDynamically(days: string[]): any {
var marked = {};
const food = {key: 'food', color: 'brown'};
const recycling = {key: 'recycling', color: 'green'};
days.forEach((day: string) => {
marked[day]['dots'] = food, recycling;
});
return marked;
}
var days: string[] = ['2024-08-21', '2024-08-22'];
var marked = addKeysAndValuesDynamically(days);
console.log(`marked = ${marked}`);
我期望它返回如上所示的“标记”对象,但是我收到一个错误: TypeError: Cannot set property 'dots' of undefined
.
我假设你刚从 javascript 转到 typescript,因为你试图避免使用类型,你可以使用接口来实现这一点:
interface KeyColor {
key: string;
color: string;
}
interface Marked {
[day: string]: {
dots: [KeyColor, KeyColor]
}
}
function addKeysAndValuesDynamically(days: string[]): Marked {
const marked: Marked = {};
const food = {key: 'food', color: 'brown'};
const recycling = {key: 'recycling', color: 'green'};
days.forEach((day: string) => {
marked[day] = { dots: [food, recycling] }
});
return marked;
}
var days: string[] = ['2024-08-21', '2024-08-22'];
var marked = addKeysAndValuesDynamically(days);
console.log(marked); // you have to log it this way to view object properties
游乐场链接