ReasonJun

Typescript : Optional / Readonly Attribute in Interface 본문

Frontend/Typescript

Typescript : Optional / Readonly Attribute in Interface

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

Optional Attribute

In TypeScript interfaces, you can make properties optional by using the ? symbol after the property name. An optional property allows you to define that a certain property may or may not be present in an object that implements the interface. This provides flexibility when working with objects that may have varying sets of properties.

 

Here's an example that demonstrates the use of optional properties in an interface:

interface Person {
  name: string;
  age?: number;
  address?: string;
}

const john: Person = {
  name: 'John',
  age: 30,
};

const jane: Person = {
  name: 'Jane',
  address: '123 Main St',
};

In this example, the Person interface has three properties: name, age, and address. The age and address properties are marked as optional by appending the ? symbol after their names. This means that objects implementing the Person interface can have or omit these properties.

 

The object john implements the Person interface and includes the age property, while the object jane includes only the name and address properties. Both objects are considered valid instances of the Person interface because they fulfill the required property name, and the optional properties can be present or absent.

 

You can access optional properties using optional chaining (?.) to handle cases where the property might not exist:

console.log(john.age); // Output: 30
console.log(john.address); // Output: undefined

console.log(jane.age); // Output: undefined
console.log(jane.address); // Output: '123 Main St'

 

 

Readonly Attribute

In TypeScript interfaces, you can mark properties as readonly to indicate that their values cannot be modified once they are assigned. This ensures that the properties remain constant and cannot be changed after initialization.

 

Here's an example that demonstrates the use of readonly properties in an interface:

interface Person {
  readonly name: string;
  readonly age: number;
}

const john: Person = {
  name: 'John',
  age: 30,
};

john.name = 'John Doe'; // Error: Cannot assign to 'name' because it is a read-only property
john.age = 31; // Error: Cannot assign to 'age' because it is a read-only property

 

728x90

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

Typescript : Overloading  (0) 2023.06.10
Typescript : Explicit this  (0) 2023.06.10
Typescript : Interface  (0) 2023.06.10
Typescript : Type Guard  (0) 2023.06.10
Typescript : Assertion  (0) 2023.06.10
Comments