How can I declare object in typescript ?
Samiran Roy
MERN Stack Web Developer | SEO Expert | content writer | English Speaking Expert |Personal Branding Strategist
In TypeScript, you can declare an object by specifying its shape using an interface or a type. Here's an example using both approaches:
Using Interface:
interface Person {
name: string;
age: number;
email?: string; // Optional property
}
const person1: Person = {
name: "John",
age: 25,
email: "[email protected]",
};
Using Type:
type Person = {
name: string;
age: number;
email?: string; // Optional property
};
const person2: Person = {
name: "Jane",
age: 30,
};
In both cases, you define the properties and their types within the curly braces. Optional properties are denoted by the ? symbol. After declaring the object type, you can create instances of it with the specified properties.
Remember that TypeScript helps catch potential errors by enforcing type safety, ensuring that your objects conform to the declared structure.