TypeScript:对象可能是“未定义的”,在具有可选的、定义良好的键的对象上进行条件创建之后

3lxsmp7m  于 2023-06-24  发布在  TypeScript
关注(0)|答案(2)|浏览(123)

我有这个密码

type t = "a" | "b"
const o: { [key in t]?: Array<number> } = {}
interface Thing {
    t: t;
}
const things: Array<Thing> = [{ t: "a"}]
for (const thing of things ) {
    if (!(thing.t in o)) o[thing.t] = []
    o[thing.t].push(1)
}

并得到错误Object is possibly 'undefined'.
TSPlayground链接

ryhaxcpt

ryhaxcpt1#

方法是

for (const thing of things) {
    ; (o[thing.t] ??= []).push(1)
}
q5iwbnjs

q5iwbnjs2#

在const o:{ [key in t]?:Array } = {}您添加了?从而使参数可选
像这样人也许能帮上忙

type t = 'a' | 'b';

  const o: { [key in t]: Array<number> } = { a: [], b: [] };
  interface Thing {
    t: t;
  }
  const things: Array<Thing> = [{ t: 'a' }];
  for (const thing of things) {
    if (!(thing.t in o)) o[thing.t] = [];
    o[thing.t].push(1);
  }

相关问题