当前位置:网站首页>Quick to typescript Guide
Quick to typescript Guide
2022-07-06 16:06:00 【Catch the king before the thief】
From:https://segmentfault.com/a/1190000040582994
TypeScript course :https://www.runoob.com/typescript/ts-tutorial.html
TypeScript Introductory tutorial :http://ts.xcatliu.com/
TypeScript Super detailed introduction ( On ):https://blog.csdn.net/Aria_Miazzy/article/details/105641241
TypeScript Detailed tutorial :https://www.jianshu.com/p/c0ca03cffa62
5 Minutes to go TypeScript:https://www.tslang.cn/docs/handbook/typescript-in-5-minutes.html
Typescript Manual Guide :https://www.tslang.cn/docs/handbook/basic-types.html
TypeScript Chinese Manual :http://www.runoob.com/manual/gitbook/TypeScript/_book/
In depth understanding of TypeScript:https://jkchao.github.io/typescript-book-chinese/
TypeScript is JavaScript with syntax for types. TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
types and @types
types and @types:https://zhuanlan.zhihu.com/p/194196536
solve TypeScript Report errors TS2304: cannot find name ' require':npm install @types/node --save-dev
1、 Why use TypeScript
TypeScript
It allows us to avoid some type
perhaps Some code results that are not what we expected
error .xxx is not defined We all know JavaScript
The error is thrown during operation , however TypeScript
The error is directly told to us in the editor , This greatly improves the development efficiency , You don't have to spend a lot of time writing a single test , It also avoids a lot of time for troubleshooting Bug
.
What is? TypeScript ?
TypeScript Is a free and open source programming language developed by Microsoft , It is JavaScript A superset of , Expanded JavaScript The grammar of .
Grammatical features
- class Classes
- Interface Interfaces
- modular Modules
- Type notes Type annotations
- Compile time type checking Compile time type checking
- Arrow function ( similar C# Of Lambda expression )
JavaScript And TypeScript The difference between
TypeScript yes JavaScript Superset , Expanded JavaScript The grammar of , So the existing JavaScript Code can be associated with TypeScript Working together without any modification ,TypeScript Provide static type checking at compile time through type annotation .
TypeScript Can deal with the existing JavaScript Code , And only for one of them TypeScript Code to compile .
2、TypeScript Advantages and disadvantages
advantage
- Generally, when we conduct joint debugging at the front and rear ends , See the field types in the interface document , and
TypeScript
It will automatically help us identify the current type . It saves us going to seefile
perhapsnetwork
Time . This is called type derivation ( We'll talk about... Later ) - Friendly prompt errors in the editor , Avoid code type implicit conversion at run time .
shortcoming
- There is a certain learning cost ,
TypeScript
There are several types of concepts in ,interface Interface
、class class
、enum enumeration
、generics Generic
Waiting for this requires us to take time to learn . - It may not be perfectly combined with some plug-in Libraries
3、TypeScript and JavaScript Operation flow
JavaScript Operation process
rely on NodeJs Environment and browser environment
- take
JavaScript
Code conversion toJavaScript-AST
- take
AST
Convert code to bytecode - Calculate bytecode during operation
TypeScript Operation process
The following operations are TSC operation . After the first three steps , The following operations continue as above .
- take
TypeScript
Code compiled asTypeScript-AST
- Check
AST
Type check on code - After type check , Compiled into
JavaScript
Code JavaScript
Code conversion toJavaScript-AST
- take
AST
Convert code to bytecode - Calculate bytecode during operation
4、TypeScript and JavaScript difference
Only by understanding the difference between the two , We can better understand TypeScript
Type system properties | JavaScript | TypeScript |
---|---|---|
How types are bound ? | dynamic | static state |
Whether there is type implicit conversion ? | yes | no |
When to check the type ? | Runtime | Compile time |
When to report errors | Runtime | Compile time |
Type binding
- JavaScript:
JavaScript
Dynamic binding type , Only the running program can know the type , Before the program runsJavaScript
Know nothing about types - TypeScript:
TypeScript
Before the program runs ( That is, compile time ) You'll know what the current type is . Of course, if the variable has no type defined , thatTypeScript
Will automatically derive the type .
Type conversion
- JavaScript: For example
JavaScript
in1 + true
Such a code fragment ,JavaScript
There are implicit transformations , At this timetrue
Will becomenumber
typenumber(true)
and 1 Add up . - TypeScript: stay
TypeScript
in ,1+true
Such code will be inTypeScript
Error reported in , Tipsnumber
Type cannot be combined withboolean
Type to operate .
When to check the type
- JavaScript: stay
JavaScript
Type can be checked only when the program is running . Types also have implicit conversions , Very pit . - TypeScript: stay
TypeScript
in , The type is checked at compile time , If it does not match the expected type, it will directly report an error in the editor 、 Red explosion
When to report errors
- JavaScript: stay
JavaScript
Exceptions can only be thrown when the program is executing ,JavaScript
There are implicit transformations , When our program executes, we can really know whether the code type is the expected type , Is the code valid . - TypeScript: stay
TypeScript in
, When you write code in an editor , If there is an error, an exception will be thrown directly , Greatly improve the efficiency , It's also convenient .
5、TypeScript Two models of
Explicit annotation types ( Type annotation )
let name: string = " New features and which methods have changed ";
let age: number = 38;
let hobby: string[] = ["write code", " Play a game "]
The explicit annotation type is , Define the type when declaring a variable ( The official word is Annotate the statement ), Let's see at a glance , Oh ~, This name
It's a string
type .
TypeScript Provide static types through type annotations to start type checking at compile time . This is optional , And it can be ignored and used JavaScript Regular dynamic types .
function Add(left: number, right: number): number {
return left + right;
}
The annotation for the basic type is number, bool and string. The weak or dynamic structure is any type .
Type annotations can be exported to a separate declaration file so that those using the type have been compiled as JavaScript Of TypeScript The type information of the script is available . Annotations can be an existing JavaScript Library statement , It's like having been for Node.js and jQuery What we did .
When the type is not given ,TypeScript The compiler uses type inference to infer types . If due to a lack of statement , No type can be inferred , Then it will default to dynamic any type .
Example : stay type.ts Create a simple area() function :
function area(shape: string, width: number, height: number) {
var area = width * height;
return "I'm a " + shape + " with an area of " + area + " cm squared.";
}
document.body.innerHTML = area("rectangle", 30, 15);
Create a index.html file :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Learning TypeScript</title>
</head>
<body>
<script src="hello.js"></script>
</body>
</html>
modify index.html
Of js File for type.js
Then compile TypeScript file : tsc type.ts
.
Browser refresh index.html file , The output is as follows :
Derivation type
let name = " New features and which methods have changed "; // It's a string type
let age = 38; // It's a number type
let hobby = ["write code", " Play a game "] // It's a string An array type
The derivation type is to remove the display annotation , The system will automatically identify the type of the current value .
6、 install TypeScript && function
install typescript
We can install... In the following two ways TypeScript:
- adopt Node.js Package manager (npm)
- Through and with Visual Studio 2012 inherited MSI. (Click here to download)
adopt npm Follow the installation steps :
1、 install npm ( installed nodejs after ,npm You can use it directly )
$ curl http://npmjs.org/install.sh | sh
$ npm --version
2、 install TypeScript npm package :
$ npm install -g typescript
After installation, we can use TypeScript compiler , The name is tsc, The compilation results can be generated js file .
To compile TypeScript file , You can use the following command :
tsc filename.ts
Once compiled , A file with the same name will be generated in the same directory js file , You can also modify the default output name through command parameters . By default, the compiler uses ECMAScript 3(ES3) For the goal, but ES5 It's also a supported option .TypeScript Added pair for upcoming ECMAScript 6 Support for the features recommended by the standard .
We know the operation tsc
Command can be compiled to generate a file , Some little friends think it's too troublesome , Each run just compiles a file, not a run , Also have to node index.js
To run . Don't worry, let's look down
ts-node plug-in unit
Let's take a look at this plug-in ts-node
, This plug-in can run directly .ts
file , And it won't compile .js
file .
npm i ts-node // function ts-node index.ts
adopt MSI Interface for file installation :
TypeScript Of Hello World
establish hello.ts file , *.ts yes TypeScript File suffix , towards hello.ts Add the following code to the file :
alert('hello world in TypeScript!');
Next , We open the command line , Use tsc Command compilation hello.ts file :
$ tsc hello.ts
In the same directory, a hello.js file , Then open the index.html The output is as follows :
7、TypeScript Basic knowledge of
Arrow function expression ( lambda expression )
lambda expression ()=>{something} or ()=>something amount to js The function in , Its advantage is that it can automatically convert this Attach to context . Example :
var shape = {
name: "rectangle",
popup: function() {
console.log('This inside popup(): ' + this.name);
setTimeout(function() {
console.log('This inside setTimeout(): ' + this.name);
console.log("I'm a " + this.name + "!");
}, 3000);
}
};
shape.popup();
In the instance this.name It's a null value :
So let's use TypeScript Arrow function of . hold function() Replace with () =>:
var shape = {
name: "rectangle",
popup: function() {
console.log('This inside popup(): ' + this.name);
setTimeout( () => {
console.log('This inside setTimeout(): ' + this.name);
console.log("I'm a " + this.name + "!");
}, 3000);
}
};
shape.popup();
The output is as follows :
Compile the backend in the above example js In file , We can see a line var _this = this;,_this stay setTimeout() The callback function of refers to name attribute .
7.1 Basic static type
stay TypeScript The basic types in are similar to us JavScript The basic types in are the same . It's just that each one is Ts It's new in there .
1. number
const count: number = 18; // Displays an annotation number type
const count1 = 18; // Do not show comments ,ts Will automatically derive the type
2. string
const str: string = " New features and which methods have changed "; // Displays an annotation string type
const str1 = " Frogman "; // Do not show comments ,ts Will automatically derive the type
3. boolean
const status: string = false; // Displays an annotation string type
const status1 = true; // Do not show comments ,ts Will automatically derive the type
4. null
const value: null = null;
// This point null Type can be assigned undefined With the js It's the same in ,null == undefined
const value: null = undefined;
5. undefined
const value: undefined = undefined;
// This point null Type can be assigned undefined With the js It's the same in ,null == undefined
const value: undefined = null;
6. void
Literally means " Invalid " , There will be <a href="javascript: void(0)"> This is control a The default behavior of label jump . Whatever you do void Method, which returns undefined. stay TypeScript in void What is the type . It also represents invalid , It's usually used only in function On , Tell people this function no return value .
function fn(): void {} // correct
function testFn(): void {
return 1; // Report errors , The return value is not accepted
}
function fn1(): void { return undefined} // Show return undefined type , It's OK, too
function fn2(): void { return null} // Show return null The type can also , because null == undefined
7. never
never " A type that will never have a value " perhaps It can also be said that " A type that can never be executed ", Represents that there will be no value for ,undefined、null It's worth it . Generally, this type will not be used , Also need not . Just know this type .
const test: never = null; // error
const test1: never = undefined // error
function Person(): never { // correct , Because of the dead cycle , Never finish
while(true) {}
}
function Person(): never { // correct , Because recursion , There will never be an exit
Person()
}
function Person(): never { // correct Code error , It can't be carried out
throw new Error()
}
8. any
any
This type represents Any 、 Any of the . I hope everyone in the project , Don't define any
type . Although it really works , So let's write TypeScript
It doesn't make any sense .
let value: any = ""; // correct
value = null // correct
value = {} // correct
value = undefined // correct
9. unknown
unknown
The type is us TypeScript
The second one any
type , It also accepts any type of value . Its English translation is Unknown , Let's take a look at chestnuts
let value: unknown = ""
value = 1;
value = "fdsfs"
value = null
value = {}
unknown and any difference
There must be some friends wondering now , EH , Then it unknown
Equivalent to any
type , What's the difference between the two . Let's take a look
let valueAny: any = "";
let valueUnknown: unknown = "";
valueAny = " Frogman ";
valueUnknown = " New features and which methods have changed "
let status: null = false;
status = valueAny; // correct
status = valueUnknown // Report errors , Can't be unknown Type assigned to null type
Let's take a look at the above , Why? any
Type can be assigned successfully , and unknown
The type doesn't work , In the sense of both of them , It's a little different ,any
Any , Any of the 、unknown
Unknown . So you give unknown
Type assignment doesn't matter for any type , Because it is an unknown type . But if you put it unknown
Type to be assigned a null
type , At this time, people null
I quit here , I don't accept unknown
type .
To put it bluntly :
- Others don't accept unknown type
- and unknown Type accept others
7.2 Object static type
Speaking of object types , We can all think of objects that contain {}
、 Array
、 class
、 function
1. object && {}
In fact, these two mean the same ,{}
、object
Represents a non primitive type , In addition to number
,string
,boolean
,symbol
,null
or undefined
Other types .
const list: object = {} // An empty object
const list1: object = null; // null object
const list: object = [] // Array objects
const list: {} = {}
list.name = 1 // Report errors The fields inside cannot be changed , But you can read
list.toString()
2. Array
const list: [] = []; // Define an array type
const list1: number[] = [1,2] // Define an array , The inside value must be number
const list2: object[] = [null, {}, []] // Define an array that must be of object type
const list3: Array<number> = [1,2,3] // Generic definition array must be number type , Generics we'll talk about later
3. class
// class
class ClassPerson = {
name: " New features and which methods have changed "
}
const person: ClassPerson = new Person();
person.xxx = 123; // This line of code reports an error , Because the... Does not exist in the current class xxx attribute
4. function
// function . Defining a variable must be of function type , The return value must be string type
const fn: () => string = () => " New features and which methods have changed "
7.3 Function type annotation
Here, the function display annotation and function parameters will not cause type derivation problems .
1. Function return type is number
function fn(a, b): number {
return a + b;
}
fn(1, 2)
2. function void
Show comments as void
type , Function has no return value .
function fn(): void {
console.log(1)
}
3. Functions do not automatically type infer
You can see the following function types , No automatic type derivation , Although our arguments are passed in 1 and 2, But the formal parameter aspect can accept any type of value , So the system can't recognize what you're passing , So here we need to define the annotation type .
function testFnQ(a, b) {
return a + b
}
testFnQ(1,2)
Let's transform .
function testFnQ(a:number, b:number) {
return a + b
}
testFnQ(1,2)
Let's take another look at the parameter object display annotation type , Also in :
Each field type can be assigned after the number .
function testFnQ(obj : {num: number}) {
return obj.num
}
testFnQ({num: 18})
7.4 Tuples Tuple
Tuples are arrays that represent the number and type of a known array , Define the type of each value in the array , It is not often used .
const arr: [string, number] = [" New features and which methods have changed ", 1]
const arr: [string, string] = [" New features and which methods have changed ", 1] // Report errors
7.5 enumeration Enum
Enum
Enumeration type , Default values can be set , If not set, it is the index .
enum color {
RED,
BLUE = "blue",
GREEN = "green"
}
// color["RED"] 0
// color["BLUE"] blue
Like above color in RED No set value , Then its value is 0, If BLUE If it is not set, its value is 1, They are increasing here . If the value is set, the set value is returned
Notice that there's another problem , Go straight to the code
Through the above study, we know enum
You can add value , You can also set the default value . But one thing to note ,enum
No, json
As flexible as objects ,enum
You cannot set a default value on any field .
Like chestnuts below ,RED
No set value , then BLUE
Set the default value , however GREEN
No settings , Now this GREEN
Will report a mistake . Because you're the second BLUE
After setting the default value , Third, it doesn't set , At this time, the code doesn't know how to increment , So wrong reporting . Another solution is that you give BLUE
You can set a numeric value , Then the third GREEN
If it is not set, it will increase , Because it's all number
type .
// Report errors
enum color {
RED,
BLUE = "blue",
GREEN
}
// good
enum color {
RED, // 0
BLUE = 4, // 4
GREEN // 5
}
such as enum
Enumeration types can also be contrasted , adopt value
check key
value . Like us json
Objects just don't support this kind of writing .
enum color {
RED, // 0
BLUE = 4, // 4
GREEN // 5
}
console.log(color[4]) // BLUE
console.log(color[0]) // RED
7.6 Interface Interface
Interface interface
What is it? , Interface interface
It is convenient for us to define a code , Multiple reuse . There are also some modifiers in the interface . Now let's get to know them .
1. How to reuse interfaces
For example, before we get to that , We don't know Interface
This thing , You may need to define a type for the object , You might do that .
const testObj: { name: string, age: number } = { name: " New features and which methods have changed ", age: 18 }
const testObj1: { name: string, age: number } = { name: " Frogman ", age: 18 }
Let's use the interface to transform .
interface Types {
name: string,
age: number
}
const testObj: Types = { name: " New features and which methods have changed ", age: 18 }
const testObj1: Types = { name: " Frogman ", age: 18 }
You can see the use of interface
Keyword defines an interface , Then assign values to these two variables , Realize reuse .
2. readonly Modifier
readonly
type , Read only status , Non modifiable .
interface Types {
readonly name: string,
readonly age: number
}
const testObj: Types = { name: " New features and which methods have changed ", age: 18 }
const testObj1: Types = { name: " Frogman ", age: 18 }
testObj.name = " Zhang San " // You cannot change name attribute , Because it's a read-only property
testObj1.name = " Li Si " // You cannot change name attribute , Because it's a read-only property
3. ? Optional modifiers
Optional modifiers to ?
Definition , Why do you need an optional modifier , Because if we don't write Optional modifiers
, that interface
All the attributes inside are required .
interface Types {
readonly name: string,
readonly age: number,
sex?: string
}
const testObj: Types = { name: " New features and which methods have changed ", age: 18}
4. extends Inherit
our interface
It can also be inherited , Follow ES6Class
Similar to class , Use extends
keyword .
interface Types {
readonly name: string,
readonly age: number,
sex?: string
}
interface ChildrenType extends Types { // this ChildrenType The interface has inherited the parent Types Interface
hobby: []
}
const testObj: ChildrenType = { name: " New features and which methods have changed ", age: 18, hobby: ["code", " badminton "] }
5. propName Expand
interface This function is very powerful , It can be written not in interface The properties inside .
interface Types {
readonly name: string,
readonly age: number,
sex?: string,
}
const testObj: Types = { name: " New features and which methods have changed ", age: 19, hobby: [] }
Above this testObj
This line of code will explode red , because hobby
Property does not exist interface
Interface , So we don't exist in the interface , I won't let others write ?. You can use it Customize It's up there propName
.
interface Types {
readonly name: string,
readonly age: number,
sex?: string,
[propName: string]: any // propName Field must be string type or number type . The value is any type , That is, arbitrary
}
const testObj: Types = { name: " New features and which methods have changed ", age: 19, hobby: [] }
Run the above code , You can see that it doesn't explode red ~
Example : Create a interface.ts file , modify index.html
Of js File for interface.js
.
interface.js The document code is as follows :
interface Shape {
name: string;
width: number;
height: number;
color?: string;
}
function area(shape : Shape) {
var area = shape.width * shape.height;
return "I'm " + shape.name + " with area " + area + " cm squared";
}
console.log( area( {name: "rectangle", width: 30, height: 15} ) );
console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );
Interface can be annotated as a type . Compile the above code tsc interface.ts There will be no mistakes , But if you add missing after the above code name The statement of parameter will report an error when compiling :
console.log( area( {width: 30, height: 15} ) );
recompile , The error message is as follows :
$ tsc hello.ts
hello.ts(15,20): error TS2345: Argument of type '{ width: number; height: number; }' is not assignable to parameter of type 'Shape'.
Property 'name' is missing in type '{ width: number; height: number; }'.
Browser access , The output is as follows :
7.7 Type
Let's take another look Type
, This is a declaration of type aliases , Alias type can only be defined as : Basic static type
、 Object static type
、 Tuples
、 Joint type
.
Be careful :type Alias cannot be defined interface
type Types = string;
type TypeUnite = string | number
const name: typeUnite = " New features and which methods have changed "
const age: typeUnite = 18
that type Type alias and interface What's the difference between interfaces
1. type I won't support it interface Statement
type Types = number
type Types = string // Report errors , Type the alias type Duplicate names are not allowed
interface Types1 {
name: string
}
interface Types1 {
age: number
}
// interface Duplicate type names can appear on the interface , If it repeats, it is ,
// To merge is to become { name:string, age: number }
first Types
Type the alias type Duplicate names are not allowed ,interface Duplicate type names can appear on the interface , If it repeats, it is , To merge is to change { name:string, age: number }
Let's take a look at interface Another situation
interface Types1 {
name: string
}
interface Types1 {
name: number
}
You can see the above two with the same name interface
Interface , The attributes inside are also the same name , But the types are different . This is the second Types1
It will explode red , Tips : Interfaces declared later , Must be consistent with the previously declared attribute type with the same name , Put the following statement name
Change its type to string
that will do .
2. type Support expression interface I won't support it
const count: number = 123
type testType = typeof count
const count: number = 123
interface testType {
[name: typeof count]: any // Report errors
}
You can see it type
Support expression , and interface
I won't support it
3. type Support type mapping ,interface I won't support it
type keys = "name" | "age"
type KeysObj = {
[propName in keys]: string
}
const PersonObj: KeysObj = { // The normal operation
name: " Frogman ",
age: "18"
}
interface testType {
[propName in keys]: string // Report errors
}
7.8 Joint type
Joint type
use |
Express , To put it bluntly, it is to satisfy one of them type
Can .
const statusTest: string | number = " New features and which methods have changed "
const flag: boolean | number = true
Take another look at chestnuts . We use function parameters to use Joint type See what happens
function testStatusFn(params: number | string) {
console.log(params.toFixed()) // Report errors
}
testStatusFn(1)
We said above , Function parameter types cannot be derived automatically , Not to mention using Joint type , The system is even more confused , The type of the current argument is not recognized . Therefore, an error is reported when accessing the method on the current type .
Next, I'll show you some Type protection
, Sounds advanced , In fact, everyone has seen these .
1. typeof
function testStatusFn(params: number | string) {
console.log(params.toFixed()) // Report errors
}
testStatusFn(1)
After transformation
// normal
function testStatusFn(params: string | number) {
if (typeof params == "string") {
console.log(params.split)
}
if (typeof params == "number") {
console.log(params.toFixed)
}
}
testStatusFn(1)
2. in
// Report errors
interface frontEnd {
name: string
}
interface backEnd {
age: string
}
function testStatusFn(params: frontEnd | backEnd) {
console.log(params.name)
}
testStatusFn({name: " Frogman "})
After transformation
// normal
function testStatusFn(params: frontEnd | backEnd) {
if ("name" in params) {
console.log(params.name)
}
if ("age" in params) {
console.log(params.age)
}
}
testStatusFn({name: " Frogman "})
3. as Assertion
// Report errors
interface frontEnd {
name: string
}
interface backEnd {
age: string
}
function testStatusFn(params: frontEnd | backEnd) {
console.log(params.name)
}
testStatusFn({name: " Frogman "})
After transformation
// normal
function testStatusFn(params: frontEnd | backEnd) {
if ("name" in params) {
const res = (params as frontEnd).name
console.log(res)
}
if ("age" in params) {
const res = (params as backEnd).age
console.log(res)
}
}
testStatusFn({age: 118})
7.9 Cross type
Cross type
It's the opposite of the union type , It USES &
Express , Cross type
Two types must exist . Here also use the above Joint type Look at the chestnuts .
interface frontEnd {
name: string
}
interface backEnd {
age: number
}
function testStatusFn(params: frontEnd & backEnd) {}
testStatusFn({age: 118, name: " New features and which methods have changed "})
Here we can see that the argument must pass in two Interface (interface) All attribute values can . Joint type Is the type passed in .
Be careful : Our interface interface An attribute with the same name appears
interface frontEnd {
name: string
}
interface backEnd {
name: number
}
function testStatusFn(params: frontEnd & backEnd) {
console.log(params)
}
testStatusFn({name: " front end "})
Properties with the same name appear in the above two interface types , But the types are different , Then the type will change to never
.
<img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/51e337707b6641e590bbb0139fabacdb~tplv-k3u1fbpfcp-watermark.image" width="90%">
7.10 Generic
Generics are TypeScript
The hardest thing to understand , Here I try to make it clear in an easy to understand way .
function test(a: string | number, b: string | number) {
console.log(a, b)
}
test(1, " New features and which methods have changed ")
Like chestnuts on it , Function parameter Annotation type
Definition string
and number
, There's no problem with calling function arguments , But there's a need , Is the argument we You must pass in the same type ( Pass in two number
type ). Although the above Joint type It can also be realized , But if we're going to add one boolean
type , that Joint type You have to add another boolean
, Then the code is too redundant .
It needs to be used Generic 了 , Generic It is specially used for uncertain types , And flexible . Most of the use of generics is to use <T>
, Of course, you can also use it casually , Such as :<Test>
、<Custom>
Fine .
function test<T>(a: T, b: T) {
console.log(a, b)
}
// The call is followed by angle brackets, which is the type of the generic , At this time, an error is reported ,
// Because the type used in the call is number, So you can only pass in the same type of
test<number>(1, " New features and which methods have changed ")
test<boolean>(true, false)
test<string>(" New features and which methods have changed ", " Frogman ")
The above uses Generic This solves the problem of passing in the same type parameter we just said , however Generic You can also use different parameters , You can define the call type as <any>
function test<T>(a: T, b: T) {
console.log(a, b)
}
test<any>(1, " New features and which methods have changed ")
But there is another problem with the above , It can pass in objects , But if we just want to pass in number
The type and string
type . Then we Generic It also provides us with constraint
type . Generic Use extends
the Type constraint , Can only choose string
、number
type .
function test<T extends number | string, Y extends number | string>(a: T, b: Y) {
console.log(a, b)
}
test<number, string>(18, " New features and which methods have changed ")
test<string, number>(" New features and which methods have changed ", 18)
At this time , Use when passing in generics ,
Comma separated , To define what each type wants to be . remember , Only the types we're not sure about , You can use generics .
7.11 modular
TypeScript
Also support import
and export
Most of the little friends here know , There's not much to say here .
// Import
import xxx, { xxx } from "./xxx"
// export
export default {}
export const name = " New features and which methods have changed "
If there is a little partner who doesn't understand , You can read my previous articles Talk about CommonJs and Es Module And the difference between them : https://juejin.cn/post/6938581764432461854
7.12 Class class
The following three modifiers are inTypeScript
Class , stayJavaScript
Class is not supported .
1. public
public
by class
The public nature of , That is, no matter in class
Inside or outside , You can visit the class
in attribute And Method . Default defined attribute And Method All are public
.
class Person {
name = " New features and which methods have changed ";
public age = 18;
}
const res = new Person();
console.log(res.name, res.age) // New features and which methods have changed 18
You can see that the print results can be displayed ,name
Attribute has no definition public
Public attribute , therefore class
Internally defined attribute And Method The default is public
Definition .
2. private
private
by class
Private property of , Only in the present class
In order to access , At present class
Namely {}
Inside the area . stay {}
It's not accessible outside private
Defined attribute And Method Of
class Person {
private name = " New features and which methods have changed ";
private age = 18;
}
const res = new Person();
console.log(res.name, res.age) // These two lines will be popular , The current property is private , Can only be accessed inside a class
class Scholl extends Person {
getData() {
return this.username + "," + this.age
}
}
const temp = new Scholl()
// Red explosion ~, Although inherited Person class , however private The definition is to access... Only in the current class , Subclasses cannot access .
console.log(temp.getData())
3. protected
protected
by class
Protective properties of , Only in The current class and Subclass You can visit . In other words, use protected
Property defined Subclass You can also visit .
class Person {
protected username = " New features and which methods have changed ";
protected age = 18;
}
const res = new Person();
console.log(res.name, res.age) // These two lines will be popular , The current property is private , Can only be accessed inside a class
class Scholl extends Person {
getData() {
return this.username + "," + this.age
}
}
const temp = new Scholl()
console.log(temp.getData()) // New features and which methods have changed ,18. You can normally access the properties of the parent class
4. implements
implements
Keywords can only be found in class
Use in , seeing the name of a thing one thinks of its function , Implement a new class , Implement all properties and methods from parent or from interface , If in PersonAll
If the existing properties and methods in the interface are not written in the class, an error will be reported .
interface frontEnd {
name: string,
fn: () => void
}
class PersonAll implements frontEnd {
name: " New features and which methods have changed ";
fn() {
}
}
5. abstract class
Abstract class use abstract
Keyword definition .abstract
Abstract methods cannot be instantiated , If , Methods in abstract classes are abstract , Then its own class must also be abstract , Abstract methods cannot write function bodies . There are abstract methods in the parent class , Then the subclass must also re the method .
// abstract class
abstract class Boss {
name = " The qin dynasty ";
call() {} // Abstract methods cannot write function bodies
}
class A extends Boss {
call() {
console.log(this.name);
console.log("A")
}
}
class B extends Boss {
call() {
console.log("B")
}
}
new A().call()
The usage scenario of this abstract class , such as A
Demand or B
The requirement just needs a public attribute , Then there are some of their own logic , You can use abstract classes , Abstract classes can only be used in TypeScript
Use in .
Example : Next, we create a class file class.ts, The code is as follows :
class Shape {
area: number;
color: string;
constructor ( name: string, width: number, height: number ) {
this.area = width * height;
this.color = "pink";
};
shoutout() {
return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
}
}
var square = new Shape("square", 30, 30);
console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Name of Shape: ' + square.name );
console.log( 'Color of Shape: ' + square.color );
console.log( 'Width of Shape: ' + square.width );
console.log( 'Height of Shape: ' + square.height );
above Shape Class has two properties area and color, A constructor (constructor()), One way is shoutout() .
Parameters in constructor (name, width and height) The scope of the is a local variable , So compile the above files , Output the error results in the browser as follows :
class.ts(12,42): The property 'name' does not exist on value of type 'Shape'
class.ts(20,40): The property 'name' does not exist on value of type 'Shape'
class.ts(22,41): The property 'width' does not exist on value of type 'Shape'
class.ts(23,42): The property 'height' does not exist on value of type 'Shape'
Next , We add public and private Access modifier .Public Members can access... Anywhere , private Members are only allowed to access... In classes . Then modify the above code , take color Declare as private, Arguments to the constructor name Declare as public:
...
private color: string;
...
constructor ( public name: string, width: number, height: number ) {
...
because color The member variable is set to private, So the following message will appear :class.ts(24,41): The property 'color' does not exist on value of type 'Shape'
Inherit : Inheritance uses keywords extends.
And then we have class.ts Add the following code at the end of the file , As shown below :
class Shape3D extends Shape {
volume: number;
constructor ( public name: string, width: number, height: number, length: number ) {
super( name, width, height );
this.volume = length * this.area;
};
shoutout() {
return "I'm " + this.name + " with a volume of " + this.volume + " cm cube.";
}
superShout() {
return super.shoutout();
}
}
var cube = new Shape3D("cube", 30, 30, 30);
console.log( cube.shoutout() );
console.log( cube.superShout() );
Derived class Shape3D explain :
- Shape3D Inherited Shape class , Also inherited Shape Class color attribute .
- In the constructor ,super Method called the base class Shape Constructor for Shape, Passed parameters name, width, and height value . Inheritance allows us to reuse Shape Class code , So we can inherit area Property to calculate this.volume.
- Shape3D Of shoutout() Method overrides the implementation of the base class .superShout() Method by using super Keyword directly returns the of the base class shoutout() Method .
- For other codes, we can complete the functions we want through our own requirements .
7.13 Namespace namespace
We learned that we can now see , I don't know if my friends find out , Whether the file in the project cannot have duplicate variables ( Whether you are the same file or other files ), Otherwise it will explode red . One of the most explicit purposes of a namespace is to solve the problem of duplicate names .
The namespace uses namespace
Keyword to define , Example :index.ts
namespace SomeNameSpaceName {
const q = {}
export interface obj {
name: string
}
}
It's like this , Just define a namespace , You can see the variables q Didn't write export keyword , This proves that it is an internal variable , Even if something else .ts The file references it , It won't be exposed . and interface This obj Interfaces can be accessed globally .
We access the current namespace on another page
1. reference introduce
/// <reference path="./index.ts" />
namespace SomeNameSpaceName {
export class person implements obj {
name: " New features and which methods have changed "
}
}
2. import
export interface valueData {
name: string
}
import { valueData } from "./xxx.ts"
At this time, after using the namespace, the problem of red explosion of duplicate names of different files can be solved .
7.14 tsConfig.json
This tsconfig
file , We compiled ts file , How to integrate ts
Compile the file into our js
file .tsc -init
This command will generate the file . Execute the order , We can see that a... Will be generated under the root directory tsconfig.json
file , There are a bunch of attributes in it .
So how can we make ts
File compiled into js
What about the documents , Direct execution tsc
The command can delete all files in the root directory .ts
All files are compiled into .js
Output the file to the project .
More configuration documents , Please refer to https://www.tslang.cn/docs/handbook/compiler-options.html
{
// include: ["*.ts"] // Execute all... Under the directory ts File conversion to js file
// include: ["index.ts"] // Only under the project index.ts The file is converted to js file
// files: ["index.ts"] // Follow include equally , Only execute the files in the current array value , At present files Must write relative path
// exclude: ["index.ts"] // exclude Except index.ts Don't execute , Everything else is done
compilerOptions: {
removeComments: true, // Remove compiled js Notes to the document
outDir: "./build", // Final output js File directory
rootDir: "./src", // ts Entry file lookup
}
}
8、 Utility type
Finally, let's talk about the utility type ,TypeScript
The standard library comes with some practical types . These utility classes are convenient interfaces Interface
Use . Here are just a few commonly used , More practical types https://www.typescriptlang.org/docs/handbook/utility-types.html
1. Exclude
Exclude one type from another , Can only be Joint type , from TypesTest
Exclude from type UtilityLast
type .
Apply to : Union type
interface UtilityFirst {
name: string
}
interface UtilityLast {
age: number
}
type TypesTest = UtilityFirst | UtilityLast;
const ObjJson: Exclude<TypesTest, UtilityLast> = {
name: " New features and which methods have changed "
}
2. Extract
Extract
Just the opposite of the one above , This is to select an assignable Joint type , from TypesTest
Only... Is selected in the type UtilityLast
type .
Apply to : Union type
interface UtilityFirst {
name: string
}
interface UtilityLast {
age: number
}
type TypesTest = UtilityFirst | UtilityLast;
const ObjJson: Extract<TypesTest, UtilityLast> = {
age: 1
}
3. Readonly
Converts all property values of an array or object to read-only . Here is just a demonstration of the object chestnut , Array is written the same way .
Apply to : object 、 Array
interface UtilityFirst {
name: string
}
const ObjJson: Readonly<UtilityFirst> = {
name: " New features and which methods have changed "
}
ObjJson.name = " Frogman " // Report errors Read only status
4. Partial
Set all properties of the object to optional . We know interface
Just don't set ?
Modifier , Then all objects are required . This utility class can convert all properties to optional .
Apply to : object
interface UtilityFirst {
name: string
}
const ObjJson: Partial<UtilityFirst> = {
}
5. Pick
Pick
Select part of object type key
value , extracted . The first parameter The target
, The second parameter union key
Apply to : object
interface UtilityFirst {
name: string,
age: number,
hobby: []
}
const ObjJson: Pick<UtilityFirst, "name" | "age"> = {
name: " New features and which methods have changed ",
age: 18
}
6. Omit
Omit
Select part of object type key
value , To filter out . The first parameter The target
, The second parameter union key
Apply to : object
interface UtilityFirst {
name: string,
age: number,
hobby: string[]
}
const ObjJson: Omit<UtilityFirst, "name" | "age"> = {
hobby: ["code", " badminton "]
}
7. Required
Required
Convert all optional attributes of the object into required attributes .
Apply to : object
interface UtilityFirst {
name?: string,
age?: number,
hobby?: string[]
}
const ObjJson: Required<UtilityFirst> = {
name: " Frogman ",
age: 18,
hobby: ["code"]
}
8. Record
Create an object result set , The first parameter is key
value , The second parameter is value
value . It is stipulated that we can only create the field values .
Apply to : object
type IndexList = 0 | 1 | 2
const ObjJson: Record<IndexList, " New features and which methods have changed "> = {
0: " New features and which methods have changed ",
1: " New features and which methods have changed ",
2: " New features and which methods have changed "
}
Reference material
- https://www.cnblogs.com/mengf...
- great TypeScript Introductory tutorial
- TypeScript Programming entity book
- TypeScript Chinese net
边栏推荐
- Luogu P1102 A-B number pair (dichotomy, map, double pointer)
- Penetration test (2) -- penetration test system, target, GoogleHacking, Kali tool
- Nodejs+vue online fresh flower shop sales information system express+mysql
- 【练习-5】(Uva 839)Not so Mobile(天平)
- The most complete programming language online API document
- 【练习-11】4 Values whose Sum is 0(和为0的4个值)
- Gartner:关于零信任网络访问最佳实践的五个建议
- Research Report on shell heater industry - market status analysis and development prospect forecast
- [exercise-8] (UVA 246) 10-20-30== simulation
- C basic grammar
猜你喜欢
随机推荐
Opencv learning log 14 - count the number of coins in the picture (regardless of overlap)
快速转 TypeScript 指南
JS调用摄像头
Shell Scripting
【练习-7】Crossword Answers
[exercise-8] (UVA 246) 10-20-30== simulation
[exercise-5] (UVA 839) not so mobile (balance)
初入Redis
Alice and Bob (2021 Niuke summer multi school training camp 1)
0-1背包問題(一)
基于web的照片数码冲印网站
[exercise-6] (UVA 725) division = = violence
Opencv learning log 31 -- background difference
洛谷P1102 A-B数对(二分,map,双指针)
Opencv learning log 32 edge extraction
Essai de pénétration (1) - - outils nécessaires, navigation
B - Code Party (girls' competition)
Determine the Photo Position
C language must memorize code Encyclopedia
Borg maze (bfs+ minimum spanning tree) (problem solving report)