Difficulties With Dictionaries In TypeScript
[!INFO]-
topic: [π¦ TypeScript]
links: What is TypeScript
source: TypeScript course by the native web
tags: #permanent-noteΒ #published
Last Modified:
=dateformat(this.file.mtime, "MMM. dd, yyyy - HH:mm")
Defining dictionaries in TypeScript can be a bit complicated because the type system gets in the way. Here are some examples of how not to do it.
Imagine a dictionary of country populations.
// Doesn't work, because empty object does not allow accessing properties.
let countries = {};
countries.germany = 80_000_000;
// Doesn't work, because object does not allow accessing properties.
let countries: object = {};
countries.germany = 80_000_000;
// Doesn't work, because Object does not allow accessing properties.
let countries: Object = {};
countries.germany = 80_000_000;
// Works, but is not very well extensible.
interface Countries {
germany?: number;
france?: number;
}
let countries: Countries = {};
countries.germany = 80_000_000;
countries.france = 66_000_000;
// Works, but accessing a property leads to always-existent values, no matter whether they have been defined or not.
interface Countries {
[ name: string ]: number;
}
let countries: Countries = {};
countries.germany = 80_000_000;
countries.france = 66_000_000;
countries.italy = 60_000_000;
// so this is the way
let countries: Record<string, unknown> = {};
countries.germany = 80_000_000;
countries.france = 66_000_000;