This year is a special year. After returning to Beijing, I was trapped at home for half a month due to the epidemic. Now I have returned to work, but I need to wear a mask all day. We also protect themselves yo, until the flowers in full bloom, and then go out well hi! Anyway, I was told to learn typescript by my boss a year ago, but my schedule was delayed until last week because my business line was too busy 😂. This article is also a study note to share with all the students. If there are any mistakes in this article, please leave a message to me!

A, aboutTypescript

TypeScript is a superset of JavaScript that provides a type system and support for ES6. It is developed by Microsoft and originated on GitHub. It was first released in October 2012 and has undergone several updates to become a force in the front-end community, not only within Microsoft, but also in Google's Angular2 development language using TypeScript. - nguyen half-stretchingCopy the code

To put it simply,TypescriptIt’s type strictJavascriptIs Java running on the front end


1. WhytsThe emergence of

Because JS is a weak type language, the data type of variables has a dynamic, high degree of freedom, only when the execution can determine the type of variables, and TS in the definition of the type of data is clear, and then with VScode plug-in configuration, really realize the static check function, simply do not be too happy! 😄


2. tsWhat are the specific advantages

  1. Type definition to make code more formal

This is the essence of TS. When creating a variable/function/interface, the specific type of data is defined, and most errors can be found at compile time, so you don’t have to rely on the runtime to check for errors every time.

  1. Increased code readability and maintainability

This is an extension of the previous point. What is the biggest headache for programmers in development? With TS, the type system is actually the best documentation, with clear instructions on what is required, what is optional, and what the data types are.

  1. Strong inclusion

Ts is a superset of JS..js files can be renamed directly to.ts

Second, basic types

Type list:

Any, string, number, Boolean, arr, tuple, enum, void, never, undefined && nullCopy the code

1. anyAny type

Any is the default type in TS, and variables of type allow values of any type. If you define a variable as any, it is no different from writing JS, which is called anyscript, haha 😄

Const name: const age: const isbool:any = true const arr:any[] = [1,2,'3',true]....Copy the code

Note ⚠️ : now that we have chosen to usetsTo write code, that should be used with cautionanyOtherwise, why do we have to go through so much trouble to learntsOf course, if we don’t specify the type of a variable when we declare it, it will be recognized as any type

2. unknowtype

The any type is inherently deprecated, but if we use any, we can’t use the many protections Typescript provides. To address any, TypeScript3.0 introduces unknown types.

let value: unknown;

value = 100;              // true
value = "Hello World";    // true
value = false;            // true
value = [];               // true
value = {};               // true
value = Math.random;      // true
value = null;             // true
value = undefined;        // true
value = new TypeError();  // true
value = Symbol("type");   // true

Copy the code

Just as all types can be assigned to any, all types can be assigned to unknown

The unknown type can only be assigned to any type and the unknown type itself. A value of the unknown type cannot be assigned to a variable of another type

let value: unknown;

// true
let value1: unknown = value;         
let value2: any = value;             // true

 // Error
let value3: boolean = value;         // Error
let value4: number = value;          // Error
let value5: string = value;          // Error
let value6: object = value;          // Error
let value7: any[] = value;           // Error
let value8: Function = value;        // Error

Copy the code

If a value is defined as unknown, it can be assigned to any other type, but if a value is of a non-any, non-unknown other type, then it cannot be assigned to an unknown type

3. stringstring

The text data type that stores strings, which can be represented by double (“”) single quotes (“”) or back single quotes (“”).

Let name:string = '3' let name2:string = '4Copy the code

Template strings can still be used:

let name: string = 'zhangsan'
let age:number = 18
let sentence: string = `Hello,my name is ${name}.
I'll be ${age + 1} years old next month.`
Copy the code

4. numberdigital

The number type, including binary, decimal, and hexadecimal, can be represented by the number type.

let age: number = 23
let hexLiteral: number = 0xf00d
let binaryLiteral: number = 0b1010
let octalLiteral: number = 0o744
Copy the code

5. booleantype

As with JS Boolean, only true and false can be assigned.

let isOpen: boolean = false
let isClose: boolean = true
Copy the code

6. ArrayAn array of

Array is the same as the js Array, but the definition is different from the above type.

(1). First typeA capital, followed by one<>Defines the data types contained in the array

Let arr: Array<any> = [1,'33',true] let arr1: Array<number> = [1,3,5,6,7] let arr2: Array<any> = [1,3,5,6,7] Array<string> = ['name'] // error , array=> ArrayCopy the code

(2). Define the data type contained in the array directly, followed by one[]

,4,6,7 let arr3: number [] = [2] let arr4: string [] = [' q ', 'a', 'n', 'useful'] let arr5: Boolean [] = [true, false, true]Copy the code

If we do not define the same type as before, the editor will report an error, which means that the values given in the following array must all match the previously defined type

Let arr6: Array<number> = ['33',3,5,'day',7] // error let arr7: number[] = ['2',true,89] boolean[] = ['3',true] // errorCopy the code

The following red line prompts:

7. tupletuples

A tuple is a strict Array that defines data types based on order and quantity.

We talked about defining an array, but the data types in an array are limited, either to a single type or to any type

Let arr: Array < any > = [' 1 ', 'add', true, 222] let arr: Array < number > =,4,5,7,8 [2]Copy the code

Both of these are too restrictive, but sometimes the order in an array is known, and we don’t want it to change, so in this video we’re going to define a hybrid mode of any type,tupleProduces:

let list:[number,string,string,boolean] = [24,'2','data',false]
Copy the code

The values must be assigned in the known order, without a single error, :

let list2: [boolean, string, number, boolean] = [99, '2', 'data', false] // error
Copy the code

8. enumThe enumeration

Enum types complement the JS standard data types,

By default, from0Start numbering the elements

enum Color {
  Red,
  Green,
  Blue
}
let colorName: string = Color[0]
alert(colorName)   // Red
Copy the code

You can also manually specify the value of the member

enum Color {
  Red = 9,
  Green,
  Blue
}
let colorName: number = Color.Blue
alert(colorName)   // 11
Copy the code

Alternatively, all assignments can be specified

enum Color {
  Red = 'red',
  Green = 'green',
  Blue = 3
}
let colorValue: string | number = Color.Blue
alert(colorValue)  // 3
Copy the code

Use in business

export enum TabKey { VISIT = 'visit', ORDER = 'order', LIVE = 'live', INTENTION = 'intention', } interface ITabList { tab: string; key: TabKey; } // TAB list export const tabList: ITabList[] = [{TAB: 'INTENTION ', key: tabkey.intention,}, {TAB:' visit ', key: tabkey.intention,}, Tabkey. VISIT,}, {TAB: 'ORDER ', key: tabkey. ORDER,}, {TAB:' LIVE ', key: tabkey. LIVE,},]; // Return the tabList object export const tabConfigMap by passing in the value specified in TabKey: Map<TabKey, ITabList> = new Map(tabList.map(item => [item.key, item])); console.log(tabConfigMap.get(TabKey.INTENTION)); // {TAB: "intention", key: "intention"}Copy the code

9. objectNonprimitive type

There has always been a question about whether there is an object type in ts 🤔 haha 🙂 because it has never been used. Object (number, string, Boolean, symbol, null, or undefined); for example: Enum Array tuple all belong to Object

  const obj: object = [2, 'q', { a: 2 }];
  console.log(obj);  // [2, 'q', { a: 2 }] 

Copy the code

It is possible to use objec for non-primitive values and when you are unsure about the type of the last returned or passed argument.

10. voidA null value

Indicates that there is no data type, null value, as opposed to any

onlynullandundefinedIt can be assigned tovoidType, so declare onevoidType but variables are useless, right

let unusable: void = null
let unusable2: void = undefined
Copy the code

When a function returns no value, it is usually assigned tovoid

function foo(): void {
  alert('This is my warning message')
}
foo()
Copy the code

Once the function is defined asvoid, then it cannot be implementedreturn

Function foo(): void {const name: string = 'foo' return name} foo()Copy the code

Or you can only returnnullorundefined

function add(): void {
  return null
}
Copy the code

11. neverThere is no

A type that represents values that do not exist. No type can be assigned to never, often used to throw an exception or return no value

Function error(message: string): never {throw new error(message)} error(' error ')Copy the code

12. undefinedandnull

These two types are subtypes of any type, and (except in strict cases) any type can be assigned undefined and null, but by themselves are not very useful, like void

let value1: number = null
let value2: string = undefined 
let value3: boolean = null
Copy the code

13. Union types

Joint type is an integrated, based on the above type can be any of values to define, use | to split each type.

We can takestringornumberAny of the following types, but no other

Let specialValue: string | number = '10' let specialValue2: string | Boolean | number = 4-trichlorobenzene [1] / / the errorCopy the code

Three, functions,

Functions are JavaScript first class citizens, so let’s look at how we define function types in TS.

1. Function return value type

Define the data type you want after the parentheses

function foo(): void {
  return null
}

function foo(): string {
  return 'aaa'
}

function foo(): boolean {
  return false
}
Copy the code

2. Function parameter types

Just like defining variables, add the type directly after the parameter

function foo(x: string, y: number, z: boolean): void {
  console.log( x , y , z )
}
Copy the code

3. Optional parameters

We add after the parameter name? In the following example, firstName is mandatory and lastName is optional

function name(firstName: string, lastName? : string): String {return firstName + lastName} // The following two invocation methods are correct: name('xiaofeng') // xiaofeng name('xiaofeng',' Zhang ') // xiaofengzhangCopy the code

Note ⚠️ : No matter how many optional arguments there are, the optional argument must come after the required one

function buildName(firstName: string, lastName: string,age? : number, job? : string): string { if (firstName) { return firstName + ' ' + lastName } else { return lastName } } let tomcat = buildName('Tom', 'Cat') let tom = buildName(undefined, 'Tom')Copy the code

4. Default parameters

You can add a default value to the parameters of a function. When the corresponding parameter is undefined, the default parameter is enabled

Function buildNeame(firstName = 'h3 ', lastName: string): String {console.log(firstName + lastName)} let res1 = buildNeame(' person ') // error Let res2 = BuildNeame (undefined, 'hu ') //Copy the code

5. Remaining parameters

Arguments are mandatory, default and optional, but sometimes, we don’t know how many arguments are passed. Just like arguments, ts also has residual arguments. To receive, you can have multiple, you can have none, and you end up in an array.

function name(firstName: string, ... restOfName: string[]): string { return firstName + ' ' + restOfName.join(' ') } let employeeName = name('Joseph', 'Samuel', 'Lucas', 'MacKinzie') // Joseph Samuel Lucas MacKinzieCopy the code

Class && inheritance

Compared to the previous class, in the same writing, add the parameter type definition and access permission Settings

1. Parameter type definition

class Person { name: string age: number job: string constructor(name: string, age: number, job: String) {this.name = name this.age = age this.job = job} print() {return 'name:' + this.name + 'age:' + this.age + ' '+ this.job}} let person: person = new person (' jojo ', 19,' jojo ') person.print() console.log(person)Copy the code

2. Access restrictions

Class has three modifiers that control access to parameters: public, protected, and private

  • Public: Public property. Members are public by default. They can be added or not, and can be accessed externally.
  • Protected: A protected property, accessible only from the inside of a class and its subclasses
  • Private: Private property. When a member is marked as: private, it can only be accessed internally by the class, not externally, nor by inheritance

In the following example,nameIs a public property,ageIs a private property,jobIs a protected property

Class Parent {public name: string private age: number protected job: string constructor(name: string, age: constructor) number, job: String) {this.name = name this.age = age this.job = job} Info () {console.log(this.name + this.age + this.job)}} // Subclass class Children extends Parent { constructor(name: string, age: number, job: String) {super(name, age, job)} // The property "age" is private and can only be accessed in class "Person", Info () {console.log(this.age)}} let child = new Children(' Children ', 22, 'DDD ') child.info() {console.log(this.age)}} let child = new Children(' Children ', 22,' DDD ') child.info()Copy the code

3. The memory

Getters and setters are used to intercept access to property members. If only GET exists, storage without set is automatically inferred to be readonly

class Hello { private name: string private job: string get name(): string { return this.name } set name(value: string) { this.name = value } get job(): String {return this.job}} let hello = new Hello() // Console.log (hello.name) // Can be assigned to hello.name = 'king five' // Log (hello.job) // Cannot be assigned to 'job' because it is a read-only property.ts(2540) hello.job = 'teacher'Copy the code

Five, the interface

In TS, the interface is used to name these types and define contracts for your code or third-party components. Use the keyword interface to define the data types of the interface parameters and give them to functions whose parameters must conform to the types defined in interface

interface params { label: string, title: string } function foo(param: Params) {console.log(param.label,param.title)} foo({label:' name ',title:' ah '})Copy the code

1. Read-only attributereadonly

We can add read-only attributes to our parameters so that they cannot be assigned again later

interface Point {
  readonly x: number
  readonly y: number
}
let p1: Point = { x: 10, y: 20 }
    p1.x = 1  // error
Copy the code

2. Optional properties?

In some cases, you don’t need to pass a parameter. , becomes an optional property

interface Point { x: number y? : number } let p1: Point = { x: 10 }Copy the code

3. Function types

The parameters and return values of a function can be defined together through an interface

interface GetInfo { (name: string|number, age: number): boolean } let getInfo: GetInfo getInfo = function(name: string, age: Number) {return Typeof (name)===typeof(age)} console.log(getInfo(' s3 ', 12)) // false console.log(getInfo(12, 12)) 13)) // trueCopy the code

Extension: In the function type check, the parameter name of the function can not be identical with the name defined by the interface. The parameter name of the function will be checked according to the order, as long as the corresponding parameter type is correct, as follows:

interface GetInfo { (name: string|number, age: number): boolean } let getInfo: GetInfo = function(label: string, num:) GetInfo = function(label: string, num:) Number) {return typeof(label)===typeof(num)} console.log(getInfo(' three ', 12)) // false console.log(getInfo(12, 12)) 13)) // trueCopy the code

4. Class – Type

Add a type definition to the class

interface ClockInterface {
    currentTime: Date;
}

class Clock implements ClockInterface {
    currentTime: Date;
    constructor(h: number, m: number) { }
}
Copy the code

5. Interface inheritance

Interfaces can also inherit from each other, so that we can copy members from one interface to another for later reuse.

interface Shape { color: string; } // Extends Shape {sideLength: number; } let square = <Square>{}; square.color = "blue"; square.sideLength = 10;Copy the code

We can also inherit multiple interfaces simultaneously, creating composite interfaces of multiple interfaces

interface Shape { color: string; } interface PenStroke { penWidth: number; } interface Square extends Shape, PenStroke { sideLength: number; } let square = <Square>{}; square.color = "blue"; square.sideLength = 10; Square. PenWidth = 5.0;Copy the code

6. Interface inheritance classes

When an interface inherits a class type, it inherits the members of the class but not its implementation. It is as if an interface declares all the members of a class, but does not provide an implementation. Interfaces also inherit to the private and protected members of the class. This means that when you create an interface that inherits a class with private or protected members, the interface type can only be implemented by that class or its subclasses (Implement).

class Control { private state: any; } interface SelectableControl extends Control { select(): void; } class Button extends Control implements SelectableControl { select() { } } class TextBox extends Control { select() { }} // Error: The "Image" type is missing the "state" attribute. class Image implements SelectableControl { select() { } }Copy the code

Six, generics

This party will analyze the boundary knowledge about TS

Base generics

Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use.

Sometimes we need a function that returns a value of the type it receives as an argument, and we use generics. We add

to the function name, where T is used to refer to any input type.

Function foo<T>(value: T): T {return value-1} foo('3') // error receives string, returns numberCopy the code

2. Multi-parameter generics

Of course, our parameters can not always receive a parameter, return a parameter, we have more multi-parameter scenarios, here to share the multi-parameter writing method.

Function resut<T, U>(arr: [T,U]): [U,T] {return [arr[1], arr[0]]; // Return [arr[1], arr[0]]; } resut([111, 'aaaa']); // ['aaaa',111]Copy the code

Of course, if we return the value reversed, we will execute a type error:

We place the mouse over the first type error and the following message pops up:

So when we have 3,4,5,6…. How to pass a label? Same principle, as follows:

Function resut<T, U, S, K, II, I >(arr: [T, U, S, K, II, I]): (arr: [T, U, S, K, II, I]); [U, T, S, K, II, i] { return [arr[1], arr[0], arr[2], arr[3], arr[4], arr[5]] } resut([111, 'aaaa', 9, true, 's', 3])Copy the code

Type assertionas

Manually specify the type of a value, but the specified type must belong to the declared type. Asserting a type that does not exist in a union type is not allowed. It protects the code from breaking.

Sometimes you’ll find that you know more about a value than TypeScript does. Usually this happens when you clearly know that an entity has a more exact type than its existing type. Type assertions are a way of telling the compiler, “Trust me, I know what I’m doing, and whatever type it was, it’s the type I’m specifying.”

Type assertions come in two forms. The first is the Angle bracket syntax, value:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
Copy the code

For anotherasgrammarvalue as type

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;
Copy the code

Eight,keyofThe operator

TypeScript allows us to iterate over a type of property and extract the name of the property using the keyof operator, as well as the value of the property as follows:

1. Get typekeyvalue

interface Point {
  x: number;
  y: number;
}

type keys = keyof Point;     // type keys = "x" | "y"

const value: keys = 'y';     // true

const value2: keys = 'z';    // false
 
Copy the code

2. Get typevaluevalue

export type IPerson = {
  name: string;
  age: number;
  job: string;
};

export const propPick = <T, K extends keyof T>(obj: T, key: K) => {
  return obj[key];
};

const person: IPerson = {
  name: 'xiaoming',
  age: 12,
  job: 'student',
};
const name = propPick(person, 'name');
console.log('name', name); // xiaoming

Copy the code

3. Separate part of the type definition from the typepick

export interface IMapping { label: string; value: number | string; } export const studyState: IMapping[] = [{label: 'all ', value: ',}, {label:' yes ', value: 1,}, {label: 'no ', value: 2,},]; type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; type PickMapping = Pick<IMapping, 'label'>; Export const studyTagConfig: PickMapping[] = [{label: 'no ',}, {label:' yes ',},];Copy the code

4. Omit part of the specified typeOmit

interface IPerson { name: string; age: number; job: string; } const person: IPerson = { name: 'xiaoming', age: 12, job: 'student', }; type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>; Type OmitPerson = {age: number; name: string; } type OmitPerson = Omit<IPerson, 'job'>; const personPart: OmitPerson = { age: 2, name: 'zzz', };Copy the code

Nine,tsSome good use practices

In this section, I will share some specific practices that I have solved through generics in time

1. Pass the specifiedkeyValue that returns the entire object or the specified value in the object

Export const studyState: IMapping[] = [{label: 'all ', value: 0,}, {label:' yes ', value: 1,}, {label: 'no ', value: 2,},]; export const studyTagConfig: Map<number | string, IMapping> = new Map( studyState.map(item => [item.value, item]), ); // Call: studyTagconfig.get (1).label // YesCopy the code

If YOU just want to returnlabelIf so, you can change the return value:

export const studyTagConfig: Map<number | string, string> = new Map( studyState.map(item => [item.value, item.lable]), ); // Call studyTagconfig.get (1) // YesCopy the code

2. Type federation

Sometimes we define A type and B type, but this is the emergence of C type, C type is A combination of A type and B type, so we can directly use A + B combination, no need to redefine.

A type:


interface IPerson {
  name: string;
  age: number;
  job: string;
}

Copy the code

Type B:

  interface IInfo {
    key: number;
    text: string;
  }

Copy the code

C Association type:

type IParams = IInfo & IPerson const params: IParams = { name: 'xiaoming', age: 12, job: 'student', key: 22, text: 'Test ',};Copy the code

TypeScript + React Hooks

– The React project was updated a few days ago, the original React project added ts esLint validation rules, the original normal page, click on ☔️ error, so combine with the React Hooks ts also need to learn, it is said to slip off, ha 😄 see if I can fly!

Note: React has been heavily implementedhooksFunction component, so the rest of the article, ishooksWrite the way oh!

0. Functional componentsHook

Hook is a new feature in React 16.8. It lets you use state and other React features without having to write a class.

First, don’t worry, the original class components are still being maintained. The link address

The advantages of hooks:

  1. No need to think about itthisAll of them can be taken and used
  2. Life cycle merging can be even less of a consideration

For more use of hooks, see: Addresses

1.propsstateType definition of

In React, we need to define the types of props and state

The code is as follows:

import React, { useState } from 'react'; import { Button, Typography } from 'antd'; interface IProps { isLoading: boolean; dataList: any[]; } const App: react. FC<IProps> = ({isLoading, dataList}) => {const [data, setData] = useState<string>(' z3 '); Const handleClick = () => {setData(' Lisi '); Console. log(' button click '); console.log(isLoading, dataList); }; Return (<> <Button onClick={handleClick}> Button </Button> < typograph.text > {data}</ typograph.text > </>); }; export default App;Copy the code

Decomposition of 2.ReactIn theTSThe type definition

Here are some of the more common type definitions I use in my work, and let’s break them down one by one

import React from 'react'; import { PaginationProps } from 'antd/es/pagination'; interface IResponseUpload { Location: string; } interface Item { label: string; value: number; } interface IStatusDict { [key: number]: { text? : string; color? : string; }; } interface IProps { name: string; age: number; isLoading: boolean; dataList: Item[]; statusDict: IStatusDict; subIdList: number[]; detail: { job: string; showPic? : boolean; }; pagination: PaginationProps; type: 1 | 2 | 3; size? : 'sm' | 'md' | 'lg' | 'mini'; width? : number; children? : React.ReactChild; header? : React.ReactNode; onChange? : (e: React.ChangeEvent | string) => void; onClick? : (e: React.MouseEvent<HTMLButtonElement>) => void; onTableFetch: (props: any) => { items: Array<any>; total: number; page: number; size: number }; onUpload: (file: File) => Promise<IResponseUpload>; }Copy the code

A. No nested base type definitions

name: string; // eg: 'aaa' age: number; // eg: 99 isLoading: Boolean; // eg: false/trueCopy the code

B. Arrays and objects have nested data type definitions

An array of

  1. Each item in the array is of the same type:
subIdList: number[]; // eg: [1,4,6,3,7] nameList: string[]; // eg: ['a','b',' I ','p'] isLoading: Boolean []; / / eg: [false, false, true, false, true]Copy the code
  1. When an array contains objects, we need to unpack them
interface Item {
  label: string;
  value: number;
}

Copy the code

Corresponding to this type of data:

const list:  Item[] = [
  { label: 'tab1', value: 1 },
  { label: 'tab2', value: 2 },
  { label: 'tab3', value: 3 },
];

Copy the code

object

1. Regular objects

interface IDetail{ detail: { job: string; showPic? : boolean; }; }Copy the code

Corresponding data:

const detailData: IDetail = {
  detail: {
    job: 'teacher',
    showPic: false,
  },
};

Copy the code
  1. An object of class array

When we encounter an array-like object, we also have to consider unpacking it

interface IStatusDict { [key: number]: { text? : string; color? : string; }; }Copy the code

Corresponding data:

Const statusDict: IStatusDict = {0: {text: 'not recruited ', color: 'green',}, 1: {text:' recruited ', color: 'blue',}, 2: {text: 'recruited ', color: 'blue',}, 1: {text:' recruited ', color: 'blue',}, 2: {text: 'not started', color: # 777777,}, 3: {text: 'in the air, color:' orange '}, 4: {text: 'has finished, color:' # DDDDDD '},};Copy the code

C. Antd component built-in type definition, direct reference

Components in Ant. Design have their own types, which are defined for the parameters of the component. If you want to know the parameter name of the specific type, you can view its type definition and refer to its type as follows:

import { PaginationProps } from 'antd/es/pagination';
import { FormComponentProps } from 'antd/es/form';

interface IProps{
    pagination: PaginationProps;
    fromProps: FormComponentProps;
}

Copy the code

D. enumeration defines our parameter range

Our arguments sometimes have an explicit range, in which case we can give an enumeration range that can only be selected from the types we give.

interface IProps{ type: 1 | 2 | 3; size? : 'sm' | 'md' | 'lg' | 'mini'; }Copy the code

e. ReactInternal component, text definition

React also provides some type definitions for you to use

interface IProps{ name: React.ReactText; children? : React.ReactChild; header? : React.ReactNode; }Copy the code
  • Reac. ReactText: contains string and number

  • ReactChild: Contains ReactText and React components

  • React.ReactNode: contains ReactChild, ReactFragment, ReactPortal, Boolean, null, and undefined.

F. Event type definition

interface IProps{ onChange? : (e: React.ChangeEvent | string) => void; onClick? : (e: React.MouseEvent<HTMLButtonElement>) => void; onTableFetch: (props: any) => { items: Array<any>; total: number; page: number; size: number }; onUpload: (file: File) => Promise<IResponseUpload>; }Copy the code

React also defines many types in the event definition, which we can refer to directly. Here are some examples

Guest officer add a collection, a point of praise, remember to come back ah, here the content is fast add whip oh…..


Write here, did not end oh! Next I will continue to add, read the article partners can add attention to oh!

Author: Christine reference: https://juejin.im/post/6844903972579344392 all rights reserved, welcome to retain the original link reproduced:)Copy the code

If you are interested in my article or have some suggestions for me to listen to 👂, you can also add wechat oh!

Email address: [email protected]

If the pro feel my article is good, you can add attention to oh!

Finally, I wish you all the best! - Rookie ChristineCopy the code