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

A Brief Analysis of MySQL Connections and Collections

Join query A join query refers to a matching quer...

Native js implementation of slider interval component

This article example shares the specific code of ...

How to operate json fields in MySQL

MySQL 5.7.8 introduced the json field. This type ...

Basic knowledge points of mysql worm replication

Worms replicate, as the name implies, by themselv...

Summary of the most commonly used knowledge points about ES6 new features

Table of contents 1. Keywords 2. Deconstruction 3...

11 Examples of Advanced Usage of Input Elements in Web Forms

1. Cancel the dotted box when the button is press...

A permanent solution to MYSQL's inability to recognize Chinese

In most cases, MySQL does not support Chinese whe...

Example of using UserMap in IMG

usemap is an attribute of the <img> tag, use...

JavaScript determines whether the browser is IE

As a front-end developer, I can’t avoid IE’s pitf...

How to choose transaction isolation level in MySQL project

introduction Let's start with our content. I ...

Do you know what are the ways to jump routes in Vue?

Table of contents The first method: router-link (...

CSS to implement sprites and font icons

Sprites: In the past, each image resource was an ...

How to use JS to check if an element is within the viewport

Preface Share two methods to monitor whether an e...

How to configure tomcat server for eclipse and IDEA

tomcat server configuration When everyone is lear...