Here is the strategy I am currently implementing:
const createMainOrientations = <T extends readonly string[]>(
mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
const temp: Orientation[] = mainOrientationsNames.map(
mainOrientationName => ({
name: mainOrientationName,
getYear(date) {
return date.getFullYear()
},
getRecordContent: getMainOrientationRecordContent
})
)
return temp as unknown as { [Index in keyof T]: Orientation }
}
const mainOrientations = createMainOrientations([
"One",
"Two",
"Three"
] as const)
Nevertheless, I find myself having to resort to
as unknown as { [Index in keyof T]: Orientation }
, which is not ideal. If not used (even by removing the type assertion from the temp
variable), it will result in an error:
Type '{ name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; }[]' is not assignable to type '{ [Index in keyof T]: Orientation; }'.ts(2322)
However, please note that
{ name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; }
corresponds to the definition of Orientation
This signifies that any information regarding length is lost after applying the map function.
Is there a more natural approach to achieve this, without relying on type assertions or at least avoiding the use of as unknown
? The aim is to have mainOrientations as a tuple of Orientation
items equal in length to the argument provided to createMainOrientations
. Therefore, it should be like
[Orientation, Orientation, Orientation]
in this instance, and not Orientation[]
.