When working with objects in TypeScript, you have the ability to define the types of keys that can be used. In this case, your keys are limited to being of type string
, while your values can be any type.
This restriction is due to TypeScript's strong typing system, where you can specify properties that an object must have in order to be considered valid:
type obj = {property1: string, property2: any};
This defines an object type that MUST contain both specified properties for it to be valid.
Since there isn't a straightforward way to define key types in TypeScript, we use square brackets as a workaround:
type obj = {[keys: string]: any};
While it may seem unnecessary for types like string
and int
, you can still utilize union types to restrict what keys can be used:
type obj = {[keys in 'key1'|'key2'|'key3']: any};
This syntax indicates that only the keys key1
, key2
, or key3
are allowed in the object.