英文:
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);
}
英文:
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'.
答案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 = '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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论