I have a specific object structure that I receive, and it looks like this:
const object = { a: 10, an: 20 };
This object has predefined keys taken from another source:
const keys = {
/**
* A long name that describes what "a" stands for.
*/
aReallyLongName: "a",
/**
* Another long name that describes what "an" stands for.
*/
anotherReallyLongName: "an"
};
To access the value 10
from object
, I use:
object[keys.aReallyLongName] // 10
Is there a way to reference aReallyLongName
instead of a
in a type-safe manner to retrieve object
's a
property?
I want to utilize the long names to refer to the short names specifically. For example, referencing a
as aReallyLongName
rather than a
, in a known type-safe manner (even serving as an alias without being part of a keys
object).
An ideal scenario would be where object.aReallyLongName
compiles to object.a
, with the compiler recognizing the expected value as a number
.
Possibly something like this:
interface Data {
/**
* A long name that describes what "a" stands for.
*/
"a" as "aReallyLongName": number;
/**
* Another long name that describes what "an" stands for.
*/
"an" as "anotherReallyLongName": number;
}
object.aReallyLongName // compile to: object.a
Use Cases
1. Customizing data obtained from APIs or libraries
API responses can include abbreviated keys or those requiring more descriptive labeling. It would be beneficial to define interface structures that interpret these abbreviations into meaningful terminology.
2. Utilizing shortened MongoDB document keys
In scenarios involving MongoDB storage optimization, using abbreviated keys may prove useful. Describing these keys and their value types while referring to them by more recognizable terms, such as in the context of a project, could enhance efficiency.