[TS Basics] Boolean type, number type, string type, array type

Boolean type, number type, string type, array type, tuple type

First look at the file directory

Insert picture description here

Boolean type (boolean) true false

index.ts
Insert picture description here
can only be assigned true/false, if other values are assigned , an error will be reported

flag = 'str' // 错误写法

Insert picture description here
It can also be written like this

flag = false

Number type (number)

index.ts

// 数字类型(number)

let a:number = 123
console.log(a)

a=12.3 // ts 对浮点型和整型数字没有区分 
console.log(a)

Insert picture description here
Error when a is other value
Insert picture description here
Insert picture description here

String type (string)

index.ts

// 字符串类型(string)

var str:string = 'this is ts'

str = '你好ts'
console.log(str)

Insert picture description here
Wrong writing
Insert picture description here
Insert picture description here
will be automatically converted to es5 grammar when using let and other es6 syntax in ts

After index.ts is
Insert picture description here
compiled, index.js
Insert picture description here
recommends using es6 syntax! !

There are two ways to define an array in the array type (array) ts

Define array writing in es5

var arr = [1, '2223', false, 'str']

The first way: define the type, the value on the right can only put the value of the defined type

// 1.第一种定义数组的方式
      let arr:number[] = [1,2,3,4,5]
      console.log(arr)

      let arr:string[] = ["js","ts","go"]
      console.log(arr)

Insert picture description here
Insert picture description here
If the type is defined and a different value is placed, an error will be reported! !
Insert picture description here
Insert picture description here
The second way: generic

    let arr:Array<number> = [11,22,33]
    console.log(arr)

    let arr: Array<string> = ["js","ts","node.js"]
    console.log(arr)

Insert picture description here
Insert picture description here
The type is fixed, and other types on the right will also report an error! !

Guess you like

Origin blog.csdn.net/weixin_43352901/article/details/108687232