javascript 对枚举值使用“includes()”时TypeScript抱怨[已关闭]

5rgfhyps  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(168)

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
7小时前关闭。
Improve this question
这里出了什么问题?我试图在一个枚举类型的数组中找到一个枚举值。但是TS抱怨了,正如你所看到的。

export enum LearningStageType {
  FUEL_DOOR_OFFSET = 'FUEL_DOOR_OFFSET',
  VEHICLE_INFO = 'VEHICLE_INFO',
  POSITIONING = 'POSITIONING',
  CYCLE_DRY_RUN = 'CYCLE_DRY_RUN',
  FINISH = 'FINISH',
}

// Type of `status` used below
export interface LearningStatus {
  vehicleId: string;
  licensePlate: string;
  countryCode: ISO3166a2CountryCode;
  // ...
  allowedStages?: LearningStageType[];

}

// Type of `stage` in code below
export type LearningStage = {
  stageType: LearningStageType;
  instructionText: string;
  instructionImage?: ImageSourcePropType;
  title: string;
  subtitle?: string;
  mainComponent: React.FC<LearningStageProps>;
  isAllowed?(status: LearningStatus, settings: LearningSettings): boolean;
};

// My code
  const stage = stages[previousStageType];

  if (skipValidation) {
    return stage;
  }
  if (stage.isAllowed) {
    return stage.isAllowed(status, settings) ? stage : null;
  }
  // The line that makes TS complain:
  if (status.allowedStages?.includes[stage.stageType]) {
    return stage;
  }
  return null;

TS错误:

(property) LearningStatus.allowedStages?: LearningStageType[] | undefined
Element implicitly has an 'any' type because expression of type 'LearningStageType' can't be used to index type '(searchElement: LearningStageType, fromIndex?: number | undefined) => boolean'.
  Property '[LearningStageType.FUEL_DOOR_OFFSET]' does not exist on type '(searchElement: LearningStageType, fromIndex?: number | undefined) => boolean'.ts(7053)
jgovgodb

jgovgodb1#

问题是您使用的includes方法不符合标准。您没有像调用函数一样调用它,而是使用了不正确的方括号表示法。正确使用includes方法的方法如下:

if (status.allowedStages?.includes(stage.stageType)) {
  return stage;
}

通过这种方式,TypeScript编译器将include识别为方法,并且不会给予错误。

相关问题