In an attempt to enhance certain areas of a codebase, I came across multiple arrays utilized to convert information from our backend into user-friendly strings - similar to the structure below:
export const MyMapping = [
{ dbLabel: 'something', screenLabel: 'Something User-friendly' },
...
];
Due to this array being present in various locations without any specific type enforcement, I decided to create the following:
export type DbLabelMapper = Record<'dbLabel' | 'screenLabel', string>;
(initially implemented as an interface)
Since the database labels were incorrectly treated as strings instead of types in other parts of the codebase, I proceeded with the following adjustments:
export const MyMapping: Array<DbLabelMapper> = [
{ dbLabel: 'something', screenLabel: 'Something User-friendly' },
...
] as const;
export type MyMappingType = typeof MyMapping[number]['dbLabel'];
I encountered an error in Typescript regarding assigning a readonly type ([...] as const
) to a mutable type (Array<DbLabelMapper>
). Therefore, I refined the mapping signature as shown below:
export const MyMapping: Readonly = [
{ dbLabel: 'something', screenLabel: 'Something User-friendly' },
...
] as const;
export type MyMappingType = typeof MyMapping[number]['dbLabel'];
However, following these modifications, MyMappingType
does not exhibit any defined types. Based on the desired outcome illustrated in my example, I expected something like
MyMappingType = 'something' | 'anotherThing' | '...'
. Am I overlooking a mistake here, or did I omit a crucial step?