Strict value check of indexed types in TypeScript

601 views Asked by At

I want to know if its possible to have a indexed type, where if a key is defined, the object is defined as well, but the key itself is not necessarily set. Example:

type Car = { model: string };
type Cars = { [id: string]: Car};
const cars: Cars = {};
const aCar = cars["a"];
console.log(aCar.model);
// no errors, but is wrong
const carModels = Object.values(cars).map(car => car.model);
// no errors, is correct

playground

type Car = { model: string };
type Cars = { [id: string]: Car | undefined};
const cars: Cars = {};
const aCar = cars["a"]; // basically, I want this to be potentially undefined
console.log(aCar.model);
// "aCar" is possibly undefined, correct error
const carModels = Object.values(cars).map(car => car.model);
// "car" is possibly undefined, bad error

playground

The problem is that Object.values will also take into account the optionality of the Cars object values.

I think the Map object would work and be typed the way I want to, but there's syntax overhead of using setters and getters.

This might be more of a language request, but as an added bonus, it would be amazing if the type would be inferred to be not optionally undefined in cases like this:

if ("foo" in cars) {
  console.log(cars["foo"])
}
1

There are 1 answers

0
JacquesB On

What you describe is possible with the noUncheckedIndexedAccess flag (available since Typescript 4.1).