当它确实存在时,属性在类型上不存在
除了Fetch API外,我还尝试使用Typescript来代表Web请求和响应。我定义了一个 inctentoryItem
,该定义了从API返回的几个字段。 Code for InventoryItem
looks similar to this:
/src/types/InventoryItem.tsx
:
type InventoryItem = {
id : number;
upc : string;
[... And so on ...]
}
Because of the nature of the API I am accessing, I need to make two requests to actually获取库存项目的所有必需数据。 I am using a function like the following to accomplish this:
async getInventoryItem<InventoryItem>(upc) : InventoryItem | Error {
let response = await fetch(url, options);
let firstItem : InventoryItem;
let secondItem : InventoryItem;
if (response.ok) {
let json = await response.json();
firstItem = json.records[0];
// Make second request for remaining fields
response = await fetch(newURL, options);
if (response.ok) {
json = await.response.json();
// Merge important field from first request into second object
secondItem.upc = firstItem.upc // <--- Issue is here
}
}
}
VSCode gives me an error when trying to assign the upc
field, claiming that Property 'upc' does not exist on InventoryItem
,但正如我上面所说的,字面上的确实存在于库存中。重新加载我的IDE并没有改变。
我很可能会以错误的方式做到这一点,因为我对打字稿几乎没有经验。但是,根据我可以知道的类型的分配正确。为什么找不到正确的字段?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类型定义
类型InventoryItem
与您在函数定义中使用的通用类型&lt; invoctoryItem&gt;
相撞。在这种情况下,通用类型正在覆盖此功能范围的定义类型。由于您没有限制通用类型
intectoryItem
是任何特定形状,因此Typescript无法读取属性upc
,因为没有迹象表明通用类型的变量库存ITEM
应具有此类属性。看起来您真的不需要这种通用类型。只需将其删除即可解决问题。
如果您需要通用类型,我建议将其重命名并限制它。
The type definition
type InventoryItem
is colliding with the generic type<InventoryItem>
that you used in the function defintion. In this case the generic type is overriding the defined type for the scope of this function.Since you did not constrain the generic type
InventoryItem
to be of any particular shape, TypeScript can not read propertyupc
since there is no indication that a variable of the generic typeInventoryItem
should have such property.It does not look like you really need this generic type. Just removing it should fix the problem.
If you need the generic type, I would suggest renaming it and constraining it.
您会无意中添加
grensics
generics 在这里。 TypeScript Generics是一个完全不同的功能,这里不需要。但是,当您创建了一种新的本地类型(用作变量)。从某种意义上说,这种新类型是覆盖
conteboryItem
您可能已经定义的。删除此内容,您对仿制药很擅长,
您可以使用不同的参数和相应的返回类型创建多个功能。我认为你不需要
You are inadvertently adding the code for
Generics
here. Typescript generics is a completely different feature and not required here. But when you doYou have created a new local type (which is used as a variable). This new type is in a sense, overriding the
InventoryItem
you might have defined outside.Remove this and you are good
With generics you can create multiple functions like this with different parameter and corresponding return types. I don't think you need that