Introduction to TypeScript interfaces

Introduction to TypeScript interfaces

Preface:

One of the core principles of TS is to type check the structures you have. The purpose of an interface is to name these types and to define a contract for your code or third-party code.

The code that is finally compiled into JavaScript code does not contain interfaces and type constraints.

1. Interface definition

The role of the interface is similar to type keyword, but it is different. Type can define simple data types, such as the following code

type str = string


This writing method cannot be applied in interfaces, where only function types, class types, and array types can be written.

interface keyword is used to define an interface in TS.

The sample code is as follows:

// Define a simple interface interface Person {
  name: string
}
//Define the get method function getPersonName(person: Person): void {
  console.log(person.name)
}
// Define the set method function setPersonName(person: Person, name: string): void {
  person.name = name
}
// Define a person object let person = {
  name: 'A bowl of porridge',
}
setPersonName(person, 'Yiwan Zhou')
// Modification successful getPersonName(person) // Yiwan Zhou

The Person interface is like a name, which is used to describe the requirements for using the interface. For example, this interface requires a name attribute, and its type is string.

It is worth noting that type checking does not check the order of properties, it only requires that the corresponding properties exist and have the same type.

2. Attributes

2.1 Optional Attributes

If a property in an interface is optional, or exists only under certain conditions, you can add a ? sign next to the property name. The sample code is as follows:

;(function () {
  // Define a simple interface interface Person {
    name: string
    // Indicates that age is optional age?: number
  }
  // Define a person object let person = {
    name: 'A bowl of Zhou',
    age: 18,
    hobby: 'coding',
  }
  //Define the get method function getPersonName(person: Person): void {
    // console.log(person.age, person.hobby) // Property 'hobby' does not exist on type 'Person'.
  }
})()

At this time, we can write or not write the sex attribute, but the hobb attribute, because it is not defined in the interface, will throw an exception when we call it.

2.2 Read-only properties

If you want to make a property a read-only property, just add readonly in front of the property.

The sample code is as follows:

;(function () {
  interface Person {
    // Set name to read-only readonly name: string
  }
  // Define a person object let person = {
    name: 'A bowl of Zhou',
  }
  // Define the set method function setPersonName(person: Person, name: string): void {
    person.name = name // Cannot assign to 'name' because it is a read-only property.
  }
  setPersonName(person, 'a bowl of porridge')
})()

3. Class Type

3.1 Inheritance interface

Like classes, interfaces can inherit from each other. This allows us to copy members from one interface to another, giving us more flexibility in splitting interfaces into reusable modules.

Interface inheritance uses the extends keyword. The sample code is as follows:

// Define two interfaces interface PersonName {
  name: string
}
interface PersonAge {
  age: number
}

// Define a Person interface that inherits from the above two interfaces. Multiple interfaces are used, separated by commas. interface Person extends PersonName, PersonAge {
  hobby: string
  // Define a method whose return value is string
  say(): string
}
let person = {
  name: 'A bowl of Zhou',
  age: 18,
  hobby: 'coding',
  // Example method say() {
    return 'A bowl of Zhou'
  },
}
//Define the get method function getPersonName(person: Person): void {
  console.log(person.name, person.age, person.hobby)
}
getPersonName(person) // Yiwan Zhou 18 coding

Used when inheriting multiple interfaces, separated by commas.

4. Function Type

In TS, interfaces can also describe interfaces of function types.

The definition of a function type interface is like a function definition with only a parameter list and a return value type. Each parameter in the parameter list requires a name and a type.

The sample code is as follows:

interface MyAdd {
    (x: number, y: number): number
}


After the definition is completed, we can use this function interface like a normal interface.

The sample code is as follows:

let myAdd: MyAdd = (x: number, y: number): number => {
    return x + y
}


The above code is equivalent to the following function definition:

let myAdd: (x: number, y: number) => number = (
    x: number,
    y: number
): number => {
    return x + y
}

This is the end of this article about TypeScript interface. For more related TypeScript interface content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • TypeScript generic usage and generic interface combination
  • TypeScript Introduction - Interface
  • Detailed explanation of interfaces in TypeScript
  • How to explain TypeScript generics in a simple way
  • TypeScript generic parameter default types and new strict compilation option
  • In-depth understanding of Typescript generic concepts in the front end
  • Do you understand interfaces and generics in TypeScript?

<<:  A brief discussion on the fun of :focus-within in CSS

>>:  Some tips for writing high-performance HTML applications

Recommend

Right align multiple elements in the same row under div in css

Method 1: float:right In addition, floating will ...

How to manually install MySQL 5.7 on CentOS 7.4

MySQL database is widely used, especially for JAV...

Comparison of the efficiency of different methods of deleting files in Linux

Test the efficiency of deleting a large number of...

Summary of Mysql slow query operations

Mysql slow query explanation The MySQL slow query...

vue-cli introduction and installation

Table of contents 1. Introduction 2. Introduction...

MySql development of automatic synchronization table structure

Development Pain Points During the development pr...

The difference between ${param} and #{param} in MySQL

The parameter passed by ${param} will be treated ...

How to install and configure SSH service in Ubuntu 18.04

Install ssh tool 1. Open the terminal and type th...

Conditional comments to determine the browser (IE series)

<!--[if IE 6]> Only IE6 can recognize <![...

How to clear the validation prompt in element form validation

Table of contents Problem scenario: Solution: 1. ...

Modification of the default source sources.list file of ubuntu20.04 LTS system

If you accidentally modify the source.list conten...

Detailed explanation of Nginx timeout configuration

I recently used nginx in a project, and used Java...

Vue + element dynamic multiple headers and dynamic slots

Table of contents 1. Demand 2. Effect 3. All code...

JavaScript super detailed implementation of web page carousel

Table of contents Creating HTML Pages Implement t...

How InnoDB implements serialization isolation level

Serialization implementation InnoDB implements se...