缺少类型 'string' 的索引签名
Index signature for type 'string' is missing
我正在尝试使用 Typescript 在 Firebase Cloud Functions 中输入我的数据:
type SpotPriceByDay = {
NOK_per_kWh: number;
valid_from: string;
valid_to: string;
}
type SpotPrices = {
[date: string]: SpotPriceByDay
}
我的 Typescript 编译器在尝试使用它时给我一个错误
let data: SpotPrices = response.data;
data = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return {[newKey]: data[key]};
});
error TS2322: Type '{ [x: string]: SpotPriceByDay; }[]' is not assignable to type 'SpotPrices'.
Index signature for type 'string' is missing in type '{ [x: string]: SpotPriceByDay; }[]'.
我试图了解如何修复此错误,但我毫无头绪。如有任何帮助,我们将不胜感激!
data
是类型 SpotPrices
的 map 但是这里的 map 函数 returns SpotPrices 对象的 array。分配地图的结果应该是解决这个问题的一种方法:
const data: SpotPrices = response.data;
const parsedData = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return { [newKey]: data[key] };
});
另一种方法是将数据类型更改为 SpotPrices
或 SpotPrices[]
:
let data: SpotPrices | SpotPrices[] = response.data;
data = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return { [newKey]: (data as SpotPrices)[key] };
});
我正在尝试使用 Typescript 在 Firebase Cloud Functions 中输入我的数据:
type SpotPriceByDay = {
NOK_per_kWh: number;
valid_from: string;
valid_to: string;
}
type SpotPrices = {
[date: string]: SpotPriceByDay
}
我的 Typescript 编译器在尝试使用它时给我一个错误
let data: SpotPrices = response.data;
data = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return {[newKey]: data[key]};
});
error TS2322: Type '{ [x: string]: SpotPriceByDay; }[]' is not assignable to type 'SpotPrices'.
Index signature for type 'string' is missing in type '{ [x: string]: SpotPriceByDay; }[]'.
我试图了解如何修复此错误,但我毫无头绪。如有任何帮助,我们将不胜感激!
data
是类型 SpotPrices
的 map 但是这里的 map 函数 returns SpotPrices 对象的 array。分配地图的结果应该是解决这个问题的一种方法:
const data: SpotPrices = response.data;
const parsedData = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return { [newKey]: data[key] };
});
另一种方法是将数据类型更改为 SpotPrices
或 SpotPrices[]
:
let data: SpotPrices | SpotPrices[] = response.data;
data = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return { [newKey]: (data as SpotPrices)[key] };
});