current position:Home>Not yet? Get you started with typescript

Not yet? Get you started with typescript

2021-08-27 04:47:13 Xiao Lang studies hard


TS Now it is used more and more , Those who learn computer have to keep learning , In order to better pursue this era , This is what Xiao Lang studied before TS Summary of time , Can quickly help you get started TS, The list here is not very complete. List some commonly used , But it can meet the usual needs , See the official documents for details , Here is just a simple introduction , I hope I can help you

Past highlights :

Quick start Vuex To It's easy to write Vuex

From understanding to going deep into virtual DOM And the implementation diff Algorithm

Write a simple vue Responsive takes you to the principle of responsive

From use to self implementation is simple Vue Router Just look at this

The essential basic knowledge of front-end interview , Although there are few, you can't help but know

1. install

TS The advantages and disadvantages of are not repeated one by one , Let's go straight to the main topic

For global installation

npm install -g typescript
 Copy code 

2. Raw data type

Nuggets code highlight, I think it conflicts with the theme , The code here is relatively simple , I'll take a screenshot directly

Let's add... After the variable : type You can specify the type of data , Setting other types will report an error

Let's first understand the types of foundations

1. character string string

Double quotes (") Or single quotation mark (') Representation string


2. Numbers number

Support Ten / sixteen / Two / 8、 ... and Base number


3. Boolean boolean

Can only be true/false



It's not very useful



It's not very useful


6. empty void

There is no type of , Use of useless return value of function void , The return value is null ( undefined


7. Any type any

Here, when the type is uncertain , You can use any Any type , Don't use it as a last resort

Unknow The type and any It can also accommodate any type ratio any Security

I don't usually use much , No introduction


7. Literal

You can only assign what you define



3. Complex type

1. Array array

Set the type of array Take this example true This will report a mistake , Do not belong to number, The elements of the array must be of a specified type The same goes for other types


2. Tuples tuple

Have studied Python My classmates should not be too strange , You can actually think of it as an array , You can declare multiple types of arrays , In this way, data of multiple data types can be inserted , Is a fixed length array


3. Interface interface

It can easily help us define Ojbect type , It is very flexible and can describe various types of objects

And java Of interface Some differences , Here's a simple look , The details are as follows


stay interface Attribute Sure Omit

Let's give height add to ?


readonly Unalterable , Once defined, it cannot be modified , Is it right? const It's kind of like , however const For variables , readonly It's for properties

Now let's put id add readonly


4. function funtion

We're going to specify the of the function Input type and Return type

stay After the parameter Colon declaration The type of parameter , stay () Back Colon declaration return type

If you pass in extra parameters, an error will be reported


We can also add Optional parameters Here we use ? that will do , In this way, we can call two parameters or three parameters without error


Optional parameters cannot be followed by formal parameters of specified type


We can add it to Becomes an optional parameter


In addition to the above declarative writing, there is also an expression writing method


With the above understanding, let's talk about Define function types The variable of

This function here is still the one above

We define mysum Specify it The type of To receive The function we defined above

() Inside is the input parameter type

=> Representative is Return value The type of

: The following are all declaration types , It has nothing to do with code logic


We just said interface Various types can be described , So we use interface To describe the function type

Be careful. Previously used => To represent the return value type

Here it is. () after : return type


5. Joint type union types

But when the type of a variable may be several types, we can use any , however any Is the scope of a little big , Less than Cannot but Don't use ,

If we know which of these types , We can use Joint type use | Separate

Take the following example ,haha May be number perhaps string


Be careful : Before the assignment , Only access Common approach 、 attribute , Take the following example ,number No, length attribute


6. object object

We direct let a: object; Isn't it meaningless , because js There are too many objects in ..

We can use


Property must be of type { name: string; age: number; } in

4. Assertion type inference

When a variable of union type is passed in above , We declare this type as number | string It cannot call length Method

The machine can't judge this type , But we know this type better than machines , We can specify the type string Here we can use Types of assertions

1. We will use as To make an assertion


2. There's another way to write it < type > Both functions are the same


5. Type guard type guard

When you encounter a union type , Use Type guard can Narrow the scope of

Implement the following method as above


Type guard except typeof outside , also instanceofin

6. class class

stay ES6 in The concept of class , stay TS Add some functions to the class , Here are just a few commonly used

First write a basic class


Let's talk about it first 3 Access modifiers

Public: The attributes or methods of modification are common stay anyplace All have access to

Private: The decorated property or method is private Only This category Medium visit

Protected: The decorated property or method is protected stay This category and In subclass Be able to access

For example, specify in the parent class money Access rights are private , Only in Parent visit , Subclass access will cause errors


We can set the access permission to protected , So subclasses can access


Static attribute static

above name money These two properties are through example To visit

Use static The attribute of modification is through class To visit , Is common to each instance

Again static Can be modified Method , use static The method of modification is called Class method , You can use classes to directly call


read-only readonly

Let's add... To the attribute readonly This property can be guaranteed read-only , Do not modify , If there is static Modifier , Write after


abstract class abstract

TS New abstract classes , Let's simply say the concept , When we write a class , You don't want to use this class directly to create instances **( Can not be new)** So let's set it as an abstract class , Make it impossible to instantiate

Can only be inherited

stay class front add to abstract Modifier ,

In an abstract class Can write Abstract method , Abstract classes have no method bodies

for instance : An abstract class of animals , There is a method called , impossible Each animal sounds the same , We can set it as an abstract method , Implement specific function subclasses ( What should be called is written by subclasses )


Encapsulation and of attributes java equally , Not here ...

7. Interface interface

Why do interfaces appear

In order to solve Inherit Plight ( One class can only inherit from another class, and cannot implement multiple inheritance )

There's another situation , people Can wash clothes , Washing machine You can also wash clothes , Washing machines and people can't find a common parent , We can take out the function of washing clothes and write it as an interface , people and Washing machine Just implement this interface

We can use implements To implement the interface


Interfaces can be implemented more


Interface can be inherited before

The following example interface inherits another interface , In this way, humans only need to implement one interface


8. enumeration enum

Constants are often used in projects , although const You can declare constants , But some constant values are in a range , Here we need to use enum To process

1. Enumeration of numbers


You can modify the initial value in the enumeration


2. String Enum


3. Constant enumeration

stay enum Add a const that will do , It improves performance

Why do you say that , I'll compile the above string enumeration into js Example , and Constant enumeration compilation Post it and compare it


Constant enumeration directly finds Week.Tuesday There's no upper part

9. Generic

Generics are like placeholders, variables , When using, we can pass the defined type as a parameter , Intact output

For example, in this example, we want to return a value , Here I write death is number


In practice, , Not necessarily. number, We can solve this problem through generics , The defined type is passed in , Return what type

A brief introduction to generics

here T Is equivalent to a placeholder , In the method ( Variable , Interface .... wait ) Add later <T>


Does it look so simple , Actually, it's really

Then I'm using getValue This way Only need Actual parameters Specify the type , Compiler, it's not stupid , Can know our parameter type , And assign them to T


Multiple parameters


In use , The wise judge Incoming type , And modify the T,U, It's really convenient


We can use interface To restrain Generic

stay T Back extends Ilen , Definition Ilen The code inside represents ,T There must be length attribute

In this way Method params.length You can't report an error


stay class Use generics


stay Interface Use generics


stay Array Use generics


In fact, there are many ways to use generics , Here's a simple introduction

10. Type the alias

Use type Alias type


11. Cross type

use & Connect

Combine the types , Variable assignment must meet Cross type


Conclusion :

This article is Xiaolang 3 Yue duoxue TS The summary of , The writing is not comprehensive, and the writing is often used , A lot more needs to be written in a comprehensive way ... Official document yyds , But you can get started quickly through this article ,, In fact, Xiaolang used TS It's been a while , The feeling is that some generics are very complex , Highly normative , Many third-party libraries don't know the hidden types , I can't understand what I just wrote , Every time you write something, you have to think about defining types , I wish I had smashed the computer ... sportive , Still have to be patient


Reference material : TS Official documents

copyright notice
author[Xiao Lang studies hard],Please bring the original link to reprint, thank you.

Random recommended