TypeScript: 在可选、明确定义的键上进行条件创建后,对象可能为 ‘undefined’。

huangapple go评论79阅读模式
英文:

TypeScript: Object is possibly 'undefined'. after conditional creation on object with optional, well-defined keys

问题

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

TS Playground link

英文:

I have this code

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)
}

And get the error Object is possibly 'undefined'.

TS Playground link

答案1

得分: 1

以下是翻译好的部分:

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

The way is to

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

答案2

得分: 0

在常量o中,使用以下方式来使参数可选:

type t = 'a' | 'b';

const o: { [key in t]?: Array<number> } = {};

类似这样的代码可能会有所帮助:

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);
}
英文:

In const o: { [key in t]?: Array<number> } = {}
You add ? so that make that param optional

somethink like this maybe can help

  type t = &#39;a&#39; | &#39;b&#39;;

  const o: { [key in t]: Array&lt;number&gt; } = { a: [], b: [] };
  interface Thing {
    t: t;
  }
  const things: Array&lt;Thing&gt; = [{ t: &#39;a&#39; }];
  for (const thing of things) {
    if (!(thing.t in o)) o[thing.t] = [];
    o[thing.t].push(1);
  }

huangapple
  • 本文由 发表于 2023年6月22日 19:52:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定