TypeScript learning (2) - ts basic type

16047416:

        A very important feature of type-declarative Ts is that the type of variables (parameters, formal parameters) in TS can be specified through type declarations. After specifying the type, when assigning a value to the variable, the ts compiler will automatically check whether the value conforms to the type declaration, assign the value if it matches, or report an error.

Table of contents

all types of ts 

type declaration

(1) Type declaration example

 (2) Literal type declaration

(3) Joint type 

(4) ts specific type-any

(5) ts specific type-unknown

(6) Type assertion

(7) ts-specific type-void

(8) object type

(9) array type

 (10) ts-specific type-tuple

(11) ts-specific type-enum

(12) Type Alias


all types of ts 

  • number, string, boolean, Object, array... are all types in js
  • TS-specific data types: tuple (ancestor), enum (enumeration), any (any type), unknown, neve

type declaration

(1) Type declaration example

let a:number
// a的类型设置为number,在以后的使用过程中a的值只能是数字
a = 10

let b:string
b = 'hello' 

let c:boolean
c = true 

let d:object
d = {}

//function 参数确定类型
function sum(a:number,b:number){
    return a+b
}
// sum('1',2) //会报错
sum(1,2)

Note : If the declaration and assignment of variables are carried out at the same time, TS can automatically perform type detection on variables

// 如果变量的声明和赋值是同时进行的,TS可以自动对变量进行类型检测
let c = false  //此时已经定义变量c 为boolean类型了
// c = 'a'  // 把其他类型的值赋值给c  就会报错
c = true

 (2) Literal type declaration

let a2:10 //在此时就给a2 定义了10这个字面量的类型,之后对a2赋值只能赋10,否则报错
a2 = 10
// a2 =11 //就会报错 

let a3:小美
a3 = 小美
// a3 = 小美 //就会报错 

(3) Joint type 

Multiple types can be concatenated using " | " (union types)

//字面量联合类型
let b2:'male' | "female"
b2 = 'male'
b2 = "female"
// b2 = 'hello' //error  当赋值是其他 就会报错
console.log("b2",b2)

//声明联合类型
let c2: boolean | string  //c2的赋值就可以是boolean 或者string  类型
c2 = 'hello'
c2 = true
//c2 = 10  //error 报错
console.log(c2)

"&"and

let j:{name:string} & {age:number}
j = {name:'小美',age:18}

(4) ts specific type-any

        Any type represented by any is not recommended; setting the type of a variable to any is equivalent to turning off TS type detection for the variable

let d2: any
d2 = 'hello'
d2 = 1
d2 = true
console.log(d2)

(5) ts specific type-unknown

        unknown represents a value of unknown type

let e2: unknown
e2 = 'hello'
e2 = 1
e2 = true
console.log(e2)

Note: When a value of unknown type is assigned to a variable of a certain type again, an error will be reported

For example:

 e3 of type unknown is assigned to s of type string Although e3 is assigned a value of type string, an error will still be reported

let e3:unknown
e3 = 'hello'
let s:string; 
s = e3 //报错 unknown类型的变量,不能直接赋值给其他变量

(6) Type assertion

        Type assertion (judgment), which can be used to tell the parser the actual type of the variable

It can solve the above problems (variables of unknown type cannot be directly assigned to other variables)

grammar:

(1)变量  as 类型
(2)<类型> 变量

example:

let e3:unknown
e3 = 'hello'
let s:string; 
s = e3 as string; //当e3类型string
//s = <string> e3;//或者
console.log(s, e3); //hello ,hello

Type assertion usage scenarios
1. Eliminate type checking errors
        In some cases, developers clearly know the type of a variable, but TypeScript's type checking

function f():void{

}

The compiler cannot infer this type. At this time, type assertion can be used to force the type of the variable to the type specified by the developer, thereby eliminating type checking errors.

2. Dealing with joint types
        When the type of a variable is a joint type of multiple types, if the developer wants to use the properties or methods of one of the types, he can use type assertion to convert it to this type for subsequent operations.

3. Dealing with any type and unknown
        Sometimes developers need to use variables of any type, but any type will reduce the type safety of the code. If the type of the variable is known explicitly, a type assertion can be used to convert it to that type to improve the type safety of the code.

(7) ts-specific type-void

There is no concept of empty value in js, void is used to represent empty

Taking function as an example, it means a function that does not return a value

function f():void{}

Declaring a variable of type void is useless because it can only be assigned the value undefined 

let a6: void = undefined // 正确的

(8) object type

let a4 : object
a4 = {}
a4 = function (){}

Everything in js is an object, so the object type is not practical in the development process

When defining an object, generally restrict the types of properties in the object

example:

let b4 : {name : string}
b4 = {name:'小美'}
//b4 = {name:18} //error
//b4 = {name:'小美',age:18} //error 多了属性 少了属性也不行


//在属性名后边加上 ?表示属性是可选的
let b5 : {name : string age ?:number};
b5 = {name:'小帅'} //可
b5 = {name:'小帅',age:88} // 可

//当不确定属性类型有多少时
//[propName : string]:any 表示任意类型的属性
let c4 : {name : string ,[propName : string]:any};
c4 = {name:'小草',age:88,gender:'男'}


When defining a function, generally control the type of the parameter passed and the type of the return value

Set function structure declaration syntax:

语法 : (形参:类型,形参:类型,...) => 返回值

example:

//d4 是一个函数,有两个number类型的参数,返回值也是number类型
let d4 :(a:number,b:number)=>number
d4 = function(n1,n2):number{
    return 3
}

(9) array type

How to declare an array:

类型[]
Array<类型>

example:

let e:string[]
e = ['a','b','c']
// e = ['a','b',1] //error

let f4: Array<number>
f4 = [1,2,3]

 (10) ts-specific type-tuple

A tuple, a tuple is an array of fixed length

grammar:

[类型,类型]
let h: [string,string ]
h = ['1','2']
// h = ['1','2','3']//error

(11) ts-specific type-enum

enumerate

enum Gender{
    Male,
    Female
}
let i :{name:string,gender:Gender}
i ={name:'小刚',gender:Gender.Male}

(12) Type Alias

        Aliasing doesn't create a new type - it creates a new name to refer to that type. Aliasing primitive types is usually of little use. Type aliases are often used with union types.

example:

type  mytype = string  //mytype等价于string
let j:mytype  
j = '哈哈哈'


type mytype  = string | number | boolean
let j :mytype  
j = '哈哈哈'
j = 18
j = true

Guess you like

Origin blog.csdn.net/weixin_42307283/article/details/131194236