1

我想知道是否有可能有一个索引类型,如果定义了一个键,那么对象也被定义了,但键本身不一定是设置的。例子:

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

操场

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

操场

问题在于,它Object.values还将考虑Cars对象值的可选性。

我认为该Map对象可以按我想要的方式工作和输入,但是使用 setter 和 getter 会产生语法开销。

这可能更像是一种语言请求,但作为额外的好处,如果在这种情况下类型被推断为不是可选的未定义,那就太棒了:

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

0 回答 0