How can I declare object in typescript ?

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.

要查看或添加评论,请登录

Samiran Roy的更多文章

  • What is React.FC while using TS with React.js??

    What is React.FC while using TS with React.js??

    In TypeScript, is a generic type provided by the React library to define the type of a functional component. stands for…

    1 条评论

社区洞察

其他会员也浏览了