typeScript之基础类型

javascript/jquery

浏览数:84

2020-7-16

AD:资源代下载服务

基础类型包括
布尔值
数值
字符串
数组
元组
枚举值
any
viod
null 和undefined
never
object
类型断言

// 布尔类型

// let bool: boolean =false

let bool :boolean

bool \= true

// bool=123

// 数值类型

let num : number

num \= 123

// num ="ppp"

num \= 0b1111

num \= 0o173

num \= 0x7b

// 字符串类型

let str:string

str \= 'acv'

str \= \`数值是${num}\`

// console.log(str)

// 数组类型

// \[1,2,3\]

let arr1 :number\[\]

arr1\=\[1\]

let arr2: Array<number\>

arr2 \= \[1,2\]

let arr3:(string|number)\[\]

arr3 \= \[1,'s'\]

  

// 元组类型

let tuple :\[number,string,boolean\]

tuple \= \[1,'d',false\]

//枚举类型

enum Roles {

SUPER\_ADMIN,

ADMIN\=4,

USER

}

// console.log(Roles.ADMIN)//4

// console.log(Roles\[4\])//ADMIN

// var Roles;

// (function (Roles) {

// Roles\[Roles\["SUPER\_ADMIN"\] = 0\] = "SUPER\_ADMIN";

// Roles\[Roles\["ADMIN"\] = 4\] = "ADMIN";

// Roles\[Roles\["USER"\] = 5\] = "USER";

// })(Roles || (Roles = {}));

// any类型

let value:any

value \= '123'

value \= 123

value \= false

const arr4:any\[\]\=\[1,2,'qw'\]

// void类型

const consoleText\=(test:string):void\=>{

console.log(test)

}

let v:void

v\=undefined

v\=null

consoleText('asd')

// null类型和undefined

let u:undefined

u \=undefined

let n:null

n \= null

num \= null

num \= undefined

// never类型

const errorFunc \= (message:string):never\=>{

throw new Error(message)

}

// errorFunc('acd')

const infiniteFunc \= ():never \=>{

while(true){}

}

// let neverVariable = (()=>{

// while(true){}

// })()

// num=neverVariable

// object

let obj \= {

name:'lkl'

}

let obj2 \= obj

obj2.name \= 'lll'

// console.log(obj)

const getObj \= (obj:object):void\=>{

console.log(obj)

}

getObj(obj2)

  

  

// 类型断言

const getLength \= (target:string|number):number\=>{

if((<string\>target).length||(target as string).length\===0){

return (<string\>target).length

}else{

return target.toString().length

}

}

console.log(getLength(5555))

作者:yang