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】
Preface
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
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 errorLet'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
4.undefined
It's not very useful
5.null
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 andany
It can also accommodate any type ratioany
SecurityI 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 tonumber
, 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 , howeverconst
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 useinterface
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
, howeverany
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 , becausejs
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 calllength
MethodThe 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 instanceof
、 in
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 useenum
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.
https://en.qdmana.com/2021/08/20210827044707099P.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich