
Today we dive into a powerful concept in TypeScript that allows for type-safe dynamic properties in objects using TypeScript generics and index signatures. Let's explore!
Declaring IDynamic Interface with Generics#
interface IDynamic<T> {
[key: string]: T;
}
The above code declares an interface named IDynamic, which is a generic interface. A generic interface allows you to specify a placeholder (T in this case) that you can fill with actual types at the time of implementation.
This IDynamic interface has a feature where any arbitrary property name (of type string) can be added to an object, with its value being the generic type T. This makes IDynamic extremely flexible for creating objects that require dynamic properties while maintaining strict type safety!
Creating Dynamic Objects#
With IDynamic in place, let's look at how we can create some objects.
const person: IDynamic<string | number> = {
id: 1,
name: "Jane",
age: 30,
gender: "female",
};
Here we are creating an object person using the IDynamic interface. We specify that T in this case is either string or number. Now our person object keys can hold either strings or numbers, all while providing compile-time type safety.
We can get more creative:
const animal: IDynamic<string | number | typeof person> = {
name: "Stacy",
age: 5,
bread: "dog",
owner: person,
};
In this block of code, we've created an animal object that can contain properties of type string, number, or even the specific structure of our person object (typeof person). Note how we use typeof to refer to the type of the person object.
This flexibility is evident in the owner property. We can assign an entire object (the person object in this case) as a value, while still maintaining a strict type structure for each property.
Conclusion#
By leveraging TypeScript's generics and index signatures, we have successfully created flexible objects that can dynamically handle different property types while retaining reliable type safety. This feature is incredibly handy for managing projects where objects' properties may not be static or consistent, providing you with the robustness of type checks and the flexibility to adjust your code as needed. TypeScript indeed takes JavaScript to another level by making it much more manageable, reliable, and fun!