Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Index signature for type 'string' is missing

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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] };
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading