xxxxxxxxxx
Copy
1interface User {
2 id: number;
3 name: string;
4 domain?: string;
5 age?: number;
6 isActive?: boolean;
7}
8
9let user: User = {
10 id: 1,
11 name: "infinitbility",
12};
13
14// Add element for dynamic key
15user["isActive"] = true;
16console.log("user", user);
xxxxxxxxxx
// RECOMMENDED TYPE-SAFE APPRORACH
// View the bottom for the unsafe approrach
// to add a property, create a type for the object
// add the property that you want to be added
// make it optional (property?: type)
// ^
type MyObject = {
property: string;
property2?: string;
}
const myObject: MyObject = {
property: 'value'
};
myObject.property2 = 'value2';
// Method without types
// Hint: you can change the type from 'any' to another type
// only do this if all values are of the same type!
const myObject: {[key: string]: any} = {
property: 'value'
};
myObject.property2 = 'value2';