首页 > 解决方案 > 打字稿无法解析联合类型的属性

问题描述

看起来我不知道一些 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/*"
  ]
}

提前致谢

标签: typescripttypes

解决方案


因为您使用的是联合类型params所以将aSearchLocationQuery a SearchBrandQuery。只有,SearchBrandQuery没有。所以在你可以使用之前,你必须缩小类型,以便知道它具有该属性。availabilitySearchLocationQueryparams.availabilityparams

一种使用类型保护的方法。例如,这没有错误:

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即使您不需要它们来进行您正在执行的搜索,也必须拥有所有属性。我得到的印象是您不想这样做(可能是因为这个原因),因为您在其他地方使用了交叉点类型。


推荐阅读