typescript - 打字稿无法解析联合类型的属性
问题描述
看起来我不知道一些 ts 特定的编译问题。
我有这些接口:
export interface CommonSearchQuery {
text: string;
category: number;
}
export type SearchBrandQuery = CommonSearchQuery & {
availability: string;
}
export type SearchLocationQuery = CommonSearchQuery & {
zip: string;
}
export type SearchQuery = SearchLocationQuery | SearchBrandQuery;
还有我的用法
export const fetchBrands = (params: SearchQuery, type: RequestType): Promise<any> => {
console.log(params.availability);
}
我收到了这个错误
TS2339: Property 'availability' does not exist on type 'SearchQuery'.
Property 'availability' does not exist on type 'SearchLocationQuery'.
我的 ts 配置
{
"compileOnSave": false,
"compilerOptions": {
"incremental": true,
"jsx": "react",
"lib": ["es6", "dom", "ES2017"],
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"noImplicitThis": true,
"strictNullChecks": true,
"declaration": true,
"baseUrl": ".",
"esModuleInterop": true,
"outDir": "dist"
},
"exclude": [
"./dist/*",
"./node_modules/*",
"./stories/*"
]
}
提前致谢
解决方案
因为您使用的是联合类型,params
所以将是aSearchLocationQuery
或a SearchBrandQuery
。只有,SearchBrandQuery
没有。所以在你可以使用之前,你必须缩小类型,以便知道它具有该属性。availability
SearchLocationQuery
params.availability
params
一种使用类型保护的方法。例如,这没有错误:
export const fetchBrands = (params: SearchQuery, type: RequestType): Promise<any> => {
if ("availability" in params) {
console.log(params.availability);
}
// ...
}
...因为当您尝试使用availability
时,守卫已经证明您正在处理 a SearchBrandQuery
,因此 TypeScript 编译器可以缩小类型。
或者,您可以使用具有所有属性的交集类型:
export type SearchQuery = SearchLocationQuery & SearchBrandQuery;
问题是params
即使您不需要它们来进行您正在执行的搜索,也必须拥有所有属性。我得到的印象是您不想这样做(可能是因为这个原因),因为您在其他地方使用了交叉点类型。
推荐阅读
- python - 如何通过套接字发送分割的音频文件?
- java - 如何在正则表达式中划分重复模式?
- android - RecyclerView 中的 SharedPreferences
- apache-spark - 重写 log4j 属性以过滤 Databricks 中的日志
- excel - Excel检查单元格是否包含列表中的文本并返回列表中的值
- php - 肥皂。PHP 中的 XML 示例请求
- c# - 如何实现泛型方法?
- java - 如何修复 Spring 数据 JPA 尝试在没有 @Query 的情况下将字符串转换为十进制
- flutter-web - Flutter Web 中的多部分文件上传
- ruby-on-rails - 如何通过运行 rake 任务并在 rails 控制台中运行相同的查询从 rails 查询中获得相同的输出