When working in TypeScript, I often come across functions that expect or return objects treated as dictionaries. My question is: what is the correct type to use in these situations?
I could go with
Record<string, any>
however, this suggestion doesn't seem to be widely supported. Instead, most people recommend using
{ [key: string]: any }
But when trying to access a property later on, it defaults to type any instead of any | undefined. This implies that for every key there will be a value (which may not always be true).
Our workaround has been creating a custom Dictionary type:
type Dictionary<K extends string, T> = {
[key in K]?: T;
}
Though effective, this solution seems like overkill considering how common this requirement is.
An alternative would be simply using
{}
However, this also allows arrays, which is undesirable.
How have you approached solving this issue correctly?
PS: Another option might involve using
{ [key: string]: any | undefined }
but this approach appears cumbersome as well.
PPS: The examples provided aren't perfect since any inherently includes undefined. Consider using a different type, such as a dictionary for numbers.