ReasonJun

Typescript : Interface 본문

Frontend/Typescript

Typescript : Interface

ReasonJun 2023. 6. 10. 12:23
728x90

In TypeScript, an interface is a way to define the structure and shape of an object. It describes the contract that an object must adhere to by specifying the names, types, and optional modifiers of its properties and methods. Interfaces play a crucial role in defining the shape of data and enabling type checking and static analysis in TypeScript.

 

Here's an example of defining an interface in TypeScript:

interface Person {
  name: string;
  age: number;
  greet: () => void;
}

In this example, we have defined an interface named Person with three properties: name of type string, age of type number, and greet which is a function that takes no arguments and returns void. The interface specifies the required properties and their types, as well as the signature of the methods.

 

Interfaces can be used to describe the structure of objects and provide type annotations for variables and function parameters:

function sayHello(person: Person) {
  console.log(`Hello, ${person.name}!`);
  person.greet();
}

const john: Person = {
  name: 'John',
  age: 30,
  greet: () => console.log('Greetings!'),
};

sayHello(john);

In this code, the sayHello function expects an argument of type Person. By specifying the type as Person, we ensure that the argument must have all the properties defined in the Person interface.

 

Interfaces can also be extended to create new interfaces based on existing ones:

interface Student extends Person {
  studentId: string;
}

const alice: Student = {
  name: 'Alice',
  age: 20,
  greet: () => console.log('Hello!'),
  studentId: 'S123456',
};

In this example, the Student interface extends the Person interface, inheriting all of its properties and methods while adding an additional studentId property.

 

Interfaces in TypeScript are primarily used for type checking, providing documentation, and enforcing object structure. They are purely a compile-time construct and do not generate any JavaScript code. They are a powerful tool for defining contracts between different parts of your codebase and promoting type safety and code maintainability.

728x90

'Frontend > Typescript' 카테고리의 다른 글

Typescript : Explicit this  (0) 2023.06.10
Typescript : Optional / Readonly Attribute in Interface  (0) 2023.06.10
Typescript : Type Guard  (0) 2023.06.10
Typescript : Assertion  (0) 2023.06.10
Typescript : Inference  (0) 2023.06.10
Comments