【问题标题】:Typescript unable to resolve property on the union type [duplicate]打字稿无法解析联合类型的属性[重复]
【发布时间】:2020-05-21 11:39:48
【问题描述】:

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

提前致谢

【问题讨论】:

  • 只有SearchBrandQuery 有空,你的意思是-> export type SearchQuery = SearchLocationQuery &amp; SearchBrandQuery; 代替吗?

标签: typescript types


【解决方案1】:

因为您使用的是union type,所以params 将是或者 SearchLocationQuery SearchBrandQuery。只有SearchBrandQueryavailabilitySearchLocationQuery 没有。因此,在您可以使用 params.availability 之前,您必须缩小 params 的类型,以便您知道它具有该属性。

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

export const fetchBrands = (params: SearchQuery, type: RequestType): Promise<any> => {
    if ("availability" in params) {
        console.log(params.availability);
    }
    // ...
}

...因为当您尝试使用 availability 时,守卫已经证明您正在处理 SearchBrandQuery,因此 TypeScript 编译器可以缩小类型。


或者,您可以使用具有所有属性的intersection type

export type SearchQuery = SearchLocationQuery & SearchBrandQuery;

问题是params 必须拥有所有属性,即使您不需要它们来进行搜索。我觉得你不想这样做(可能是因为这个原因),因为你在其他地方使用了交叉点类型。

【讨论】:

    【解决方案2】:

    你的逻辑有问题。 SearchQuerySearchLocationQuerySearchBrandQuery。其中之一拥有财产availability。所以编译器会抱怨availability不是这两种类型的联合,这会导致错误

    TS2339: Property 'availability' does not exist on type 'SearchQuery'.
     Property 'availability' does not exist on type 'SearchLocationQuery'.
    

    所以你必须检查它们的类型,例如使用 in 运算符,例如

    export const fetchBrands = (params: SearchQuery, type: RequestType): Promise<any> => {
      if ("availability" in params) {
         console.log(params.availability); // works fine
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2022-01-04
      • 2020-11-30
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多