Encountered a similar issue post-building. The challenges were related to utilizing numbers and enum values as keys in objects. Here's some guidance for those facing this in the future.
Enums Used as Keys
export enum MyEnum {
one = 'stringOne',
two = 'stringTwo',
}
export const someMap = {
[ MyEnum.one ]: 'valueOne',
[ MyEnum.two ]: 'valueTwo',
};
Upon compilation, someMap
will be transformed into a type resembling...
export declare const someMap: {
[ MyEnum.one ]: string;
[ MyEnum.two ]: string;
};
Note that the keys remain as enum values and not strings, which typescript/angular might not approve of because it anticipates something like...
export declare const someMap: {
[ x: string ]: string;
};
To resolve this, consider...
1) Explicitly Define Type for someMap
export interface ForceStringType {
[product: string]: string;
}
export const someMap: ForceStringType = {
[ MyEnum.one ]: 'valueOne',
[ MyEnum.two ]: 'valueTwo',
};
2) Use string
Type for Keys in someMap
export const someMap: ForceStringType = {
[ MyEnum.one as string ]: 'valueOne',
[ MyEnum.two as string ]: 'valueTwo',
};
Numbers Employed as Keys
const CONSTANT_ONE = 123;
const CONSTANT_TWO = 321;
export const someMap = {
[ CONSTANT_ONE ]: 'valueOne',
[ CONSTANT_TWO ]: 'valueTwo',
};
Post-transformation, someMap
will manifest as...
export declare const someMap: {
[ CONSTANT_ONE ]: string;
[ CONSTANT_TWO ]: string;
};
The keys persist as constants/numbers instead of strings, prompting typescript/angular to expect...
export declare const someMap: {
[ x: string ]: string;
};
A potential solution is...
Convert Numbers to Strings for Key Assignment in someMap
export declare const someMap: {
[ `${CONSTANT_ONE}` ]: string;
[ `${CONSTANT_TWO}` ]: string;
};
Note: Accessing values from someMap
using constants/numbers as keys should function correctly as typescript automatically converts them to strings. However, maintaining consistency by explicitly converting to strings is advisable.
const valueOne: string = someMap[ CONSTANT_ONE ];
// vs
const valueOne: string = someMap[ `${CONSTANT_ONE}` ];