💻 Tech
Typescript is a statically typed language, meaning that the type of a variable is known at compile time. This makes it easier to catch errors and prevents unexpected behavior. For example, the code below doesn’t specify what type of value someMapping is. The Typescript language service in VS Code shows this in the return statement at line 9: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ hello: string; foo: string; }'.
function getMappingValue(val: string): string {
const someMapping =
{
hello: 'world',
foo: 'bar'
}
return someMapping[val] ?? val;
}
Although the code above will still work, it doesn’t conform to the best practices of Typescript. To fix this, the code below added a type to someMapping. This tells the compiler that someMapping is an object with string keys and string values.
function getMappingValue(val: string): string {
const someMapping: { [key: string]: string } =
{
hello: 'world',
foo: 'bar'
}
return someMapping[val] ?? val;
}