Record with required keys and string index

Viewed 352

This is what I want

type Report = {
  branches: number; // should be required
  functions: number; // should be required
  lines: number; // should be required
  statements: number; // should be required
};

const report: Report = {
  branches: 10,
  functions: 19,
  lines: 54,
  statements: 67,
}

but I can’t do this

const items = Object.keys(report).map(key => report[key])

typescript (version 4.3.5) shows the following error on report[key]:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Report'. No index signature with a parameter of type 'string' was found on type 'Report'.ts(7053)

So I try this

export type Report = {
  [key: string]: number;
  branches: number;
  functions: number;
  lines: number;
  statements: number;
};

but now it allows something like

const withFoo: Report = {
  branches: 25.3,
  imABug: 45, // should not be allowed!
  functions: 20.1,
  lines: 70.01, 
  statements: 45,
},
1 Answers

That's because you are creating an array of strings with Object.keys() and trying to map to Report object, which I feel is just bad implementation.

Why don't you try this for iterating over the properties instead:

type Report = {
  branches: number; // should be required
  functions: number; // should be required
  lines: number; // should be required
  statements: number; // should be required
};

const foo: Report = {
  branches: 10,
  functions: 19,
  lines: 54,
  statements: 67,
}


Object.entries(foo).map(([key, value]) => console.log(key, value));
Related