“This is the 7th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

We’ve talked a lot about TS, but in this video we’re going to look at generics

The introduction of the other content before can be moved on:

  • Class inheritance and abstract classes in TS in a minute
  • Classes and modifiers in TS, do you know
  • Are you unfamiliar with the interface in TS?
  • Can you figure out type assertion and type guard in TS?
  • Compared with JS, TS has more types
  • In TS, the corresponding data type is JS

The generic

The official introduction to generics is as follows:

In software engineering, it is important not only to create consistent, well-defined apis, but also to consider reusability. The ability of components to support not only current data types but also future data types gives you a lot of flexibility when building large systems.

In languages like C# and Java, generics can be used to create reusable components that can support multiple types of data. This allows users to use components with their own data types.

You can think of generics as broad types, which are commonly used for classes and functions, one by one

A generic class

Generics can be used with classes and constructors, for example:

class Person<T>{
    private _value: T;
    constructor(val: T) {
        this._value = val; }}let p = new Person<number> (12)
Copy the code

As above,

means passing a T type, passing the specific type only on new. T is variable modifiable, but it’s very common when you talk about TypeScript types before you write T and you talk about arrays, which is essentially a generic class

let a = new Array<number>();
Copy the code

Generic function

Generics can be used with ordinary functions, for example:

function fn<T> (arg: T) :T {
    return arg;
}
fn<number> (12);
Copy the code

The idea is to pass in a type as a special argument, whether used for a class or a function

It is important to note that generics can also “inherit”, but in terms of limiting scope for example

class Person<T extends Date>{
    private _value: T;
    constructor(val: T) {
        this._value = val; }}let p1 = new Person(new Date())

class MyDate extends Date{}
let p2 = new Person(new MyDate())
Copy the code

END

That’s all for this article. If you have any questions, please point out