6 Practical Tips for TypeScript Development

6 Practical Tips for TypeScript Development

This article summarizes some of my experiences in developing applications using TypeScript. Before I say that, I recommend a VSCODE plugin called quokka.js that allows you to execute TS code immediately.

How to use, ctrl+shipt+p, enter the keyword quokka

After pressing Enter, the code will be executed immediately after entering

1. Determine the entity type before development

Before formal coding, if there is no interface document, it is best to get the data dictionary and define the entity types in the project according to the data dictionary. For example, if there are user tables and enterprise tables in the data dictionary, we can create a types folder and put the corresponding types into different files. The directory is as follows:

types
    user.ts
    corp.ts
    ...

It is recommended to use interface to define entity types, which is more semantic than type.

interface User{
    id:string
    name:string
}

2. When requesting an interface, you only need to define the fields you need to use

When defining a type, you only need to define the fields you need to use. Unused fields do not need to be defined. Because the type of data returned by the backend requires the front end to specify the type and then TS makes a judgment. If the front end does not specify the type, TS has no way to judge it.

For example, the data returned by the backend is as follows:

user:{
    id:1,
    name:'xiaoming',
    sex:0
}

The defined types are as follows:

interface User{
    id:number,
    name:string
}

In this case, TS will only check whether there is an id and name in the user, and ignore sex.

3. Use enumeration types

Data structures such as gender (male and female), administrator type (super administrator, ordinary user), and member type (ordinary user, VIP, super VIP) are suitable for definition using enumeration types, which can also be used as values.

For example:

//Use enumeration type to define member type enum UserType{
    Common=0,
    VIP=1,
    SuperVIP=2
}
class User{
    id:string
    name:string
    type:UserType
}
let userList:User[]=[]

userList.push({
    id:'001',
    name:'Jack',
    type:UserType.SuperVIP //The type defined by the enumeration type can be used as a value})

Enumeration types can also be strings, as shown below. The usage is the same as above.

enum UserType{
    Common = 'DiaoSi',
    VIP='LowBVIP',
    SuperVIP='SuperVIP'
}

4. The type of DOM element should be given normally

For DOM elements, don't use any, they have types.
Generally speaking, all tags inherit from HTMLElement, and different tags have different types. This type is often routine. For example, the type of the video element is HTMLVideoElement, the type of the div element is HTMLDivElement, the type of the canvas element is HTMLCanvasElement, and so on. In fact, there are not many commonly used types, just list them briefly:

let element:HTMLElement=null

let video:HTMLVideoElement=null

let div:HTMLDivElement=null

let canvas:HTMLCanvasElement = null

let e:Event =null //Event object e.target

Be sure to give DOM element types so you can get code hints

Here is a supplement on how to give the type when uploading a file. Bind the onChange method to the Input element. The method is as follows:

onChange(event: Event): void {
  if ((event.target as HTMLInputElement).files && (event.target as HTMLInputElement).files.length) {
    const [file] = event.target.files;
  }
}

5. How to give the type of the object

There is a function that receives an object as a parameter. How should the type be given?

First of all, don't give any, don't give any at every turn, it's lower-level, think about what the object contains, a key, a value. The key must be a string type. The value depends on the specific needs. Maybe your value can only be a number or a string, then use number|string. If anything is acceptable, then use any.

//Define the type of the object, the key is usually a string, and the value can be given to the interface ObjType{
	[key:string]:any
}
function deepCopy(obj:ObjType){
    for(let key in obj){
        console.log(obj[key])
    }

}

let obj={name:"Jack"}
deepCopy(obj)

6. How to give the type when assigning a value to a structure

You have a function that receives an object and deconstructs the parameters in the object. How do you give the type of the object property obtained by the structure? The code is as follows:

const user={
    name:'Jack',
    age:10,
    friends:[{id:0,name:'Peter',connect:100},{id:1,name:'Alice',connect:69}]
}

interface Friend{
    id:number,
    name: string,
    connect:number
}


function handleFriends({friends}){//How to give the type of friends friends.map(item=>item.connect)
}

Think for 10 seconds.

10

9

8

7

6

5

4

3

2

1

Post the answer:

interface Friend{
    id:number,
    name: string,
    connect:number
}

function handleFriends({friends}:{friends:Friend[]}){
    friends.map(item=>item.connect)
}

This is more commonly used in react hooks.

Summarize

This is the end of this article about sharing tips for TypeScript development. For more relevant TypeScript development tips, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Practical TypeScript tips you may not know
  • TypeScript references resource files and prompts that they cannot be found when handling exceptions
  • ​​​​​​​Share 7 Practical TypeScript One-Liners

<<:  Ubuntu 18.0.4 MySQL 8.0.20 installation and configuration method graphic tutorial

>>:  How to install Apache service in Linux operating system

Recommend

Recommend several MySQL related tools

Preface: With the continuous development of Inter...

Implement QR code scanning function through Vue

hint This plug-in can only be accessed under the ...

Example code for implementing the "plus sign" effect with CSS

To achieve the plus sign effect shown below: To a...

Detailed explanation of the use of filter properties in CSS

The filter attribute defines the visual effect of...

iview implements dynamic form and custom verification time period overlap

Dynamically adding form items iview's dynamic...

6 inheritance methods of JS advanced ES6

Table of contents 1. Prototype chain inheritance ...

Detailed example of IOS database upgrade data migration

Detailed example of IOS database upgrade data mig...

How to set up a shared folder on a vmware16 virtual machine

1. Set up a shared folder on the virtual machine:...

Let's talk in detail about the difference between unknown and any in TypeScript

Table of contents Preface 1. unknown vs any 2. Th...

8 tips for Vue that you will learn after reading it

1. Always use :key in v-for Using the key attribu...