typescript TS类型保护未检测到非空类对象属性

5kgi1eie  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(234)

TypeScript有以下问题。存在以下类型的类属性AmplitudeFeatureFlags| {}={};默认情况下等于一个空对象。我有一个方法,它接收枚举类型的属性名arg,以便从上面显示的类属性中检索一些值。但是TS显示了下面代码中描述的错误。
我哪里做错了?

export enum AmplitudeFeatureFlagNames {
  addTeamMembersFromUserMenu = 'addTeamMembersFromUserMenu',
  inAppHandRaiser = 'inAppHandRaiser',
}

type AmplitudeFeatureFlagWithPayload<Payload extends object = {}> = {
  key: string;
  payload?: Payload;
};

export type AmplitudeFeatureFlags = {
  [AmplitudeFeatureFlagNames.addTeamMembersFromUserMenu]: AmplitudeFeatureFlagWithPayload;
  [AmplitudeFeatureFlagNames.inAppHandRaiser]: AmplitudeFeatureFlagWithPayload;
};

class User {
  private amplitudeFeatureFlags: AmplitudeFeatureFlags | {} = {};

    getAmplitudeFeatureFlagPayload(flagName: AmplitudeFeatureFlagNames) {
      if (flagName in this.amplitudeFeatureFlags) {
    
    **//ERROR on the line below:**
    //Element implicitly has an 'any' type because expression of type 
   //'AmplitudeFeatureFlagNames' can't be used to index type '{} | 
    //AmplitudeFeatureFlags'.
    //Property '[AmplitudeFeatureFlagNames.addTeamMembersFromUserMenu]' does not exist on 
    //type '{} | AmplitudeFeatureFlags'.

        **return this.amplitudeFeatureFlags[flagName]?.payload;**
      }
  }
}
niknxzdl

niknxzdl1#

这是因为this.amplitudeFeatureFlags并不总是AplitudeFeatureFlags类型。
private amplitudeFeatureFlags: AmplitudeFeatureFlags | {}
因此typescript知道它可能是{}类型,因此{}[key: AmplitudeFeatureFlagNames]隐式地是any类型。
您可能需要将声明更改为更具描述性的内容:
private amplitudeFeatureFlags: Partial<AmplitudeFeatureFlags> = {}
编写代码:

export enum AmplitudeFeatureFlagNames {
  addTeamMembersFromUserMenu = 'addTeamMembersFromUserMenu',
  inAppHandRaiser = 'inAppHandRaiser',
}

type AmplitudeFeatureFlagWithPayload<Payload extends object = {}> = {
  key: string;
  payload?: Payload;
};

export type AmplitudeFeatureFlags = {
  [AmplitudeFeatureFlagNames.addTeamMembersFromUserMenu]: AmplitudeFeatureFlagWithPayload;
  [AmplitudeFeatureFlagNames.inAppHandRaiser]: AmplitudeFeatureFlagWithPayload;
};

class User {
  private amplitudeFeatureFlags: Partial<AmplitudeFeatureFlags> = {};

    getAmplitudeFeatureFlagPayload(flagName: AmplitudeFeatureFlagNames): AmplitudeFeatureFlagWithPayload['payload'] | undefined {
      if (flagName in this.amplitudeFeatureFlags) {
        return this.amplitudeFeatureFlags[flagName]?.payload;
      }
      return undefined
  }
}

相关问题