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;**
}
}
}
1条答案
按热度按时间niknxzdl1#
这是因为
this.amplitudeFeatureFlags
并不总是AplitudeFeatureFlags
类型。private amplitudeFeatureFlags: AmplitudeFeatureFlags | {}
因此typescript知道它可能是
{}
类型,因此{}[key: AmplitudeFeatureFlagNames]
隐式地是any
类型。您可能需要将声明更改为更具描述性的内容:
private amplitudeFeatureFlags: Partial<AmplitudeFeatureFlags> = {}
编写代码: