英文:
Optional property does not exist on const object type
问题
我有一些类似这样的代码:
const props = {
a: {
optional: "foo",
mandatory: "bar",
},
b: {
mandatory: "blaz",
},
} as const;
const propsICareAbout: (keyof typeof props)[] = [];
for (const prop of propsICareAbout) {
if (props[prop].optional) {
doStuff(props[prop].optional);
}
}
但是当我尝试访问 props[prop].optional
时,它给我返回了这个错误:
Property 'optional' does not exist on type '{ readonly mandatory: "blaz"; }'.
请注意,propsICareAbout
是空的。无论它是否为空或为 [ 'a', 'b' ]
或其他任何值,我都会收到相同的错误。我尝试过以下方式:
const opt = "optional" in props[prop] ? props[prop].optional : null;
但仍然收到相同的错误。
英文:
I have some code like this:
const props = {
a: {
optional: "foo",
mandatory: "bar",
},
b: {
mandatory: "blaz",
},
} as const;
const propsICareAbout: (keyof typeof props)[] = [];
for (const prop of propsICareAbout) {
if (props[prop].optional) {
doStuff(props[prop].optional);
}
}
but it gives me this error when I try to access props[prop].optional
:
Property 'optional' does not exist on type '{ readonly mandatory: "blaz"; }'.
Notice that propsICareAbout
is empty. I get this error regardless of if it's empty or if it's ['a', 'b']
or whatever. I tried doing
const opt = "optional" in props[prop] ? props[prop].optional : null;
but still got the same error.
答案1
得分: 2
声明一个用于 props[prop]
的单独变量,并使用 in
运算符进行检查:
const propsICareAbout: (keyof typeof props)[] = [];
for (const propName of propsICareAbout) {
const prop = props[propName];
if ('optional' in prop) {
prop.optional;
}
}
英文:
Declare a separate variable for props[prop]
and check with in
operator:
const propsICareAbout: (keyof typeof props)[] = [];
for (const propName of propsICareAbout) {
const prop = props[propName];
if ('optional' in prop) {
prop.optional;
}
}
答案2
得分: 0
自从你在所有键和其相应属性上都有一个循环,所以在所有子对象中都没有“optional”键,因此你遇到了这个问题。
请按照下面的方式修改你的代码并检查:
const props = {
a: {
optional: "foo",
mandatory: "bar",
},
b: {
mandatory: "blaz",
},
} as const;
const propsICareAbout: (keyof typeof props)[] = ["a"];
for (const prop of propsICareAbout) {
if ("optional" in props[prop]) {
doStuff(props[prop].optional);
}
}
英文:
Since you are having a loop on all the keys and its respective properties, you do not have the "optional" key in all sub-objects and hence you are running into the issue.
Please modify your code as mentioned below and check:
const props = {
a: {
optional: "foo",
mandatory: "bar",
},
b: {
mandatory: "blaz",
},
} as const;
const propsICareAbout: (keyof typeof props)[] = ["a"];
for (const prop of propsICareAbout) {
if ("optional" in props[prop]) {
doStuff(props[prop].optional);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论