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

CSS3+Bezier curve to achieve scalable input search box effect

Without further ado, here are the renderings. The...

The problem of Vue+tsx using slot is not replaced

Table of contents Preface Find the problem solve ...

Detailed explanation on how to get the IP address of a docker container

1. After entering the container cat /etc/hosts It...

Detailed explanation of VueRouter routing

Table of contents vue router 1. Understand the co...

How to use rem adaptation in Vue

1. Development environment vue 2. Computer system...

Using js to implement simple switch light code

Body part: <button>Turn on/off light</bu...

Mysql error: Too many connections solution

MySQL database too many connections This error ob...

HTML embed tag usage and attributes detailed explanation

1. Basic grammar Copy code The code is as follows...

HTTP and HTTP Collaboration Web Server Access Flow Diagram

A web server can build multiple web sites with in...

Quick understanding and example application of Vuex state machine

Table of contents 1. Quick understanding of conce...

Vue achieves seamless carousel effect (marquee)

This article example shares the specific code of ...

MySQL join buffer principle

Table of contents 1. MySQL join buffer 2. JoinBuf...

CSS writing format, detailed explanation of the basic structure of a mobile page

1. CSS writing format 1. Inline styles You can wr...

Solution to the error when calling yum in docker container

When executing yum in dockerfile or in the contai...

Example method to view the IP address connected to MySQL

Specific method: First open the command prompt; T...