Object with Dynamic Properties
In this approach, TypeScript to create objects with dynamic properties, allowing flexibility in adding and accessing properties without a predefined structure.
Example: In this example, we define an object oB with dynamic properties, initially containing various data types. It then dynamically adds rating and email properties and logs the object to the console.
Javascript
// TypeScript let oB: { [key: string]: any } = { name: "w3wiki" , age: 15, isActive: true , Desire: [ "Content Writing" , "Contest" , "Potd" ], address: { street: "Sector-136" , city: "Noida" , State: "Uttar Pradesh" }, }; oB.rating = 4.5; oB.email = "support@w3wiki.org" ; console.log(oB); |
Output:
{
name: 'w3wiki',
age: 15,
isActive: true,
Desire: [ 'Content Writing', 'Contest', 'Potd' ],
address: { street: 'Sector-136', city: 'Noida', State: 'Uttar Pradesh' },
rating: 4.5,
email: 'support@w3wiki.org'
}
Reference: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any
TypeScript any Type
In TypeScript, any type is a dynamic type that can represent values of any data type. It allows for flexible typing but sacrifices type safety, as it lacks compile-time type checking, making it less recommended in strongly typed TypeScript code. It allows developers to specify types for variables, function parameters, and return values, enhancing code quality and maintainability. However, there are situations where you may encounter dynamic or untyped data, or when working with existing JavaScript code. In such cases, TypeScript provides the ‘any’ type as a flexible solution.