TypeScript (TS) basic content detailed introduction

Table of contents

1. TypeScript concept

Two, TypeScript features

3. Development environment configuration

4. Getting to know ts for the first time

5. TypeScript type declaration

1、any:

2, number digital type 

3 string string type 

4 boolean Boolean type 

Represents logical values: true and false.

5 array types

6-tuple type

7 enum enumeration type

8 void None of any type

9 null type

10 undefined types

11 never type

12 unknown types

13 Function types

14 object types 

15 types of aliases

16 Arrow functions

 6. Variable declaration

7. Literal statement


1. TypeScript concept

A language built on top of JavaScript . Microsoft has added some syntax on the basis of js. The design goal of TypeScript is to develop large-scale applications, which can be compiled into pure JavaScript, and the compiled JavaScript can run on any browser.

Two, TypeScript features

  1. Static type (strong type), the type is determined at the time of declaration, and modification is not allowed afterwards.
  2. TypeScript can process existing JS and only compile TS code, perfecting the determination of JS.
  3. Open source (mature community), cross-platform, all support Js code, you can use TS.
  4. Rich configuration items, powerful development tool support, etc.

3. Development environment configuration

1. Download node.js

Download address:
Download | Node.js Chinese Network

2. Configure domestic mirroring

npm config set registry

https://registry.npmmirror.com

3. Global installation

Install command: npm i -g typescript

Check version: tsc -v

4. Getting to know ts for the first time

1. Open the vscode editor and create a file with the suffix .ts in your directory

2. The code content is as follows:

let str:string; //声明变量的类型
str = 'Hello,ts' //赋值的类型只能是上面定义的类型
console.log(str);

This code means that we declare a str and define a string type for him, and then we assign a value to him

But the content we assign can only be the type we defined for str above, that is, the string type. Finally print str

3. Run

(1) First we need to open the terminal under the current file

(2) Then compile the file, enter the command in the terminal: tsc xxx.ts, xxx is the file name of the ts you created

(3) Execute the js file, node xxx.js, xxx is the same as above

We can see the code result

5. TypeScript type declaration

5.1 Basic types

1、any

A variable declared as any can be assigned any type of value (string, number, Boolean, etc.). ​​​​​​

let str:any;//任意类型
str = 123
str = '456'
str = true
console.log(str);

Let's take a look at the result by printing, and the result is the value we assigned last time.

2, number digital type 

A double-precision 64-bit floating-point value. It can be used to represent integers and fractions.

let age:number;
age = 15
console.log(age);

This is easy to understand, numbers, js has learned

3 string string type 

String type, text defined with single quotes, double quotes, template strings (backticks).

let realname:string;
realname=`我的姓名是`+'枕头睡不醒'
console.log(realname);

4 boolean Boolean type 

Represents logical values: true and false.

5 array types

The array type is a bit different, you can take a closer look

(1) Add [ ] after the type, the array is a string

let realname:string[];
realname = ['枕头睡不醒','枕头睡不着','大耳朵图图']
console.log(realname);

 (2) Use the Fan type Array

The meaning here is that first of all, an angle bracket is added after the array type, and any is written in it, which means that the value inside can be of any type

let persons:Array<any>;
persons=['枕头睡不醒',18]
console.log(persons);

 

6-tuple type

The tuple type is used to represent an array with a known number and type of elements. The types of each element do not have to be the same, and the types of the corresponding positions need to be the same.

let zs:[string,number,number];
zs = ['张三',14,18]
console.log(zs);

7 enum enumeration type

Enumerated types are used to define collections of values

What do you mean, let's just look at the code hehehe

enum days{Sun, Mon, Tue, Wed, Thu, Fri, Sat}
console.log(days.Sun);
console.log(days.Mon);
console.log(days.Tue);
console.log(days.Wed);

Is it very strange to see here, why is the number printed out? In fact, it is a digital enumeration. If it is not initialized, the default initialization value is 0 , and each item after that is +1 , so this is the result.

What if there is an initialization value?

enum days{Sun, Mon=10, Tue, Wed, Thu, Fri, Sat}
console.log(days.Sun);
console.log(days.Mon);
console.log(days.Tue);
console.log(days.Wed);

 If there is initialization, on the basis of the initialization value, each item is +1, as long as it is not the first value, the first value still starts from 0.

Summarize:

If the digital enumeration is not initialized , the default initialization value is 0 , and each item is +1

If there is initialization , on the basis of the initialization value, each item +1

Also, do not assign values ​​to the above attributes in the grammar, which will cause errors.

8 void None of any type

void is used to identify the type of return value of the method, indicating that the method has no return value.

Declaring a variable of type void is not very useful, because you can only assign undefined and null to it;

Declare a method with no return value:

function say():void{
    console.log('hello,ts!')
}
say()

9 null type

There is no need to introduce this one. It is often seen in js, indicating that the object value is missing.

10 undefined types

This is also an old acquaintance, initializing variables but undefined values.

let realname
console.log(realname);

11 never type

never is a subtype of other types, including null and undefined, representing values ​​that never occur.

For example, a function throws an exception:

function hello(str:string):never{
	throw new Error(str);
}

12 unknown types

The unknown type can be assigned to any type, but it cannot be assigned to others.

Here we will mention a type assertion , what does it mean? Come, look directly at the code

let realname:unknown;
realname ="张三"
realname =19

Type assertion, because I have  an unknown type in front of me, I don’t know what type he said, so I directly add a type to him when copying later. There are two ways of writing

Writing method one:

let realname:unknown;
realname ="张三"
str = realname as string //类型断言 断言他是字符串
console.log(realname);

Writing method two:

let realname:unknown;
realname ="张三"
str = <string>realname;
console.log(realname)

Summarize:

Type assertions can be used to manually specify the type of a value, allowing variables to change from one type to another.

13 Function types

function sum(a:number,b:number):number{
    return a+b
}

console.log(sum(1,2));

It should be noted here that the values ​​a and b we defined are both of type number, so what we return must also be of type number

14 object types 

(1) The simplest, this is actually useless

let p:object;
p={
    realname:'张三',
    age:18
}

(2) Each attribute limit "dead"

let P1:{realname:string,age:number}//定义类型
P1 = {realname:"张三",age:19} //赋值需要上面定义保持一致

(3) The types of my attributes above are all restricted, so I must pass a value, so what if I don't want to pass a value to one of them? Then need help ? That's right, it's a question mark

let p:{realname:string,age?};
p={realname:'张三'}

Look, the result will not report an error, it is very "magic"

There is another situation, that is, when our attribute name is uncertain, there is also a solution to this drop

let p:{realname:string,[propName:string]:any}
p={realname:'张三'}
P = {realname:"张三",age:19}

When the attribute name is uncertain, define propName, this propName is defined casually, everyone likes it, but it is better to be semantic, any is the type

15  types of aliases

Speaking of now, some people will be curious, can I customize the alias of the type, of course it is also possible, we need to use type

type mytype = string
let a:mytype;
a='123' //error

16 Arrow functions

The format can be defined (in fact, it defines the function format we use below)

let sum:(a:number,b:number)=>number;
sum = function(a:number,b:number):number{
    return a+b
}
 console.log(sum(1,2));

 6. Variable declaration

1 Naming rules

var [variable name] : [type] = value;

例:let str:string = "hello";

(1) Variable names can contain numbers and letters.

(2) Except for the underscore _ and the dollar $ sign, it cannot contain other special characters, including spaces.

(3) Variable names cannot start with numbers.

(4) Do not use name for the variable, otherwise it will have the same name as the name attribute under the global window object in DOM.

2 statement not set

var [variable name] : [type];

Declare the type of variable, but there is no initial value, the variable value will be set to undefined;

3 The declaration does not set a type

var[variable name] = value;

Declares a variable and initializes its value, but does not set its type. The variable can be of any type:

7. Literal statement

see three examples

let a:100
 a=100 

let sex:"男"|"女"
sex="男"

let flag:boolean |string
flag=true

The first one defines a, which is directly similar to assignment, it can only be 100, and nothing else

The second one defines that there are two values ​​in sex, the vertical bar in the middle of male or female represents or, that is, it can only be male or female

The third is similar to the second, d defines the Boolean type, then they can only be true or false

This is the end of today's sharing, let's work hard, let's go.

Guess you like

Origin blog.csdn.net/weixin_52984349/article/details/128134365