javascript - 打字稿:使用 UNION 运算符时出错
问题描述
我在 Typescript 中使用 OR 运算符来定义产品可以是ProductI
OR类型CartResponseInterface.Product
结构为
product: ProductI | CartResponseInterface.Product
但是当我试图获取 id 并将其存储在一个变量productId
中时
productId= product.id || product.productId
我得到下面提到的错误
Error:1
Property 'id' does not exist on type 'ProductI | Product'.
Property 'id' does not exist on type 'Product'.ts(2339)
Error2:
Property 'productId' does not exist on type 'ProductI | Product'.
Property 'productId' does not exist on type 'ProductI'.ts(2339)
产品模型.ts
export interface ProductI {
id?: string;
name: string;
price: number;
.
.
.
}
购物车-response.model.ts
export interface Product {
productId: string;
name: string;
totalPrice: number;
.
.
.
}
有人可以告诉我如何解决这个问题吗?
解决方案
您可以使用类型断言来强制类型,然后检查产品的 id。
const productId = (product as ProductI).id || (product as Product).productId;
// or
const productId = (<ProductI>product).id || (<Product>product).productId;
话虽如此,除非您必须这样做,否则我不建议这样做。应该有更好的方法来利用 Typescript 的类型。
推荐阅读
- c# - 尝试从 C# 调用长期运行的存储过程异步时失败
- django - django-rest-framework 覆盖创建函数在 ModelSerializer 上不起作用
- c# - 避免对未定义的 #if 代码进行 Unity 错误检查
- html - 我的问题是关于那些讨厌的 HTML 边框
- php - 如何在for循环中打印所有结果?
- java - StringBuffer 等于字符串但不工作
- python - 当第一个逗号出现时,超过 25 个单词的行被拆分
- python - ModuleNotFoundError:导入 win32com 时 IDLE 中没有名为“win32api”的模块
- python - 如何通过 python 在我的笔记本电脑上打开 .ebc (ebcdic) 文件?
- android - 从主模块启动库模块中的活动