Reputation: 305
I am trying to type my data in Firebase Cloud Functions using Typescript:
type SpotPriceByDay = {
NOK_per_kWh: number;
valid_from: string;
valid_to: string;
}
type SpotPrices = {
[date: string]: SpotPriceByDay
}
My Typescript compiler gives me an error when trying to use this
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; }[]'.
I have tried to understand how I can fix this error, but I have no clue. Any help would be appreciated!
Upvotes: 2
Views: 1772
Reputation: 50910
data
is a map of type SpotPrices
but the map function here returns an array of SpotPrices objects. Assigning the result of the map should be a way to resolve this:
const data: SpotPrices = response.data;
const parsedData = Object.keys(data).map((key) => {
const newKey = new Date(key).toISOString();
return { [newKey]: data[key] };
});
Another way would be changing type of data to either SpotPrices
or 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] };
});
Upvotes: 2