When it comes to JavaScript converting undefined
into strings for object keys, there seems to be a safe aspect in this scenario. Ignoring the error might actually be acceptable. Here's an example situation:
enum LeftEnum {
Required = 0,
Hidden = 1,
Optional = 2
};
enum RightEnum {
Required = 1,
DontShow = 2,
Optional = 3
};
type LeftObjectType = {
Show?: LeftEnum
};
type RightObjectType = {
Display: RightEnum
};
const convertLeftToRight = {
[LeftEnum.Required]: RightEnum.Required as const,
[LeftEnum.Hidden]: RightEnum.DontShow as const,
[LeftEnum.Optional]: RightEnum.Optional as const,
undefined: RightEnum.Optional as const
};
const lefts: LeftObjectType[] = [
{}, // undefined -> optional or 3
{Show: LeftEnum.Hidden}, // 1 -> dontShow or 2
{Show: LeftEnum.Required}, // 0 -> required or 1
{Show: LeftEnum.Optional} // optional -> optional or 3
];
const newRight: RightObjectType[] = lefts.map(left => ({
// Type 'undefined' cannot be used as an index type.(2538)
Display: convertLeftToRight[left.Show]
}));
// produces correct results
console.log(newRight);
// no error
const a: RightEnum.Optional = convertLeftToRight["undefined"];
// Type 'undefined' cannot be used as an index type.(2538)
const b: RightEnum.Optional = convertLeftToRight[undefined];
In this context, since we are confident that using undefined
will not cause any issues and there is no possibility of confusion with "undefined"
, it may be reasonable to bypass the check.
However, I find the restriction on utilizing undefined
for index types puzzling. TypeScript appears to recognize that using undefined
as an object key works fine, as evident from including "undefined"
leading to an error regarding multiple properties with the same name:
const convertLeftToRight= {
[LeftEnum.Required]: RightEnum.Required as const,
[LeftEnum.Hidden]: RightEnum.DontShow as const,
[LeftEnum.Optional]: RightEnum.Optional as const,
null: RightEnum.Optional as const,
undefined: RightEnum.Optional as const,
["undefined"]: RightEnum.Optional as const,
[undefined]: RightEnum.Optional as const,
"undefined": RightEnum.Optional as const,
"Undefined": RightEnum.DontShow as const
};
The object documentation highlighting the key as the blue keyword
undefined</code further adds to the confusion when compared to the green string <code>"Undefined"
or light green numbers.
https://i.sstatic.net/AwORw.png
Even if the string "undefined"
is employed:
https://i.sstatic.net/1ASc7.png