TypeScript语法(1) 数据类型

117 阅读4分钟

typeScript碎碎念

官网:www.typescriptlang.org/

  • 前提:javascript 缺点: 没有类型检测的机制

  • 定义:typeScript是拥有类型的JavaScript超集,他可以编辑成普通干净完整的JavaScript代码

  • 有两个工具可以将typeScript代码转为JavaScript代码

  • 搭建环境:ts-node 1.tsc:typeScript compiler 按照 npm install typescript -g 2.配置ts-node环境 npm install ts-node -g 3.npm install tslib @types/node -g 依赖包

  • 搭建环境:webpack 1.npm install typeScript -D 2.

6c0389aaf092deda6a0484d848d58b0.png

3.ts init

image.png

变量的声明

  • 1.类型注解 数据类型叫类型注解

    1. var/let/const
  • 3.string和String

  • 4.类型推导 默认情况下进行赋值时 会将赋值的值类型作为前面标识符的类型

  • 格式:var/let/const 标识符:数据类型 = 赋值

  • let name:string = "ddd"
    
  • //string:javascript中字符串的类型  一般用小写的
    
  • //String  javascript中的字符串包装类的类型
    
数组类型
    1.数组类型 数组中要存放相同类型的数据
    const names1:Array<string> = ["ddd"]//不推荐
    const names2:string[] = []//推荐
    
对象类型 (默认推导)
   const info = {
      name:"ddd"
    }
    
 null类型
   const n1:null = null 
   
 undefined类型
   let n2:undefined = undefined
   
 symbol类型
    const title1 = new Symbol("title")
    const title2 = new Symbol("title")
    const info={
        [title1]:"coder",
        [title2]:"老师"
    }
     export {}

typescript 类型

数据类型

any类型 (不想给js添加具体类型时)

let message:any="hello world"
message = 123

unKnown类型(描述不确定的变量)

function foo(){
    return "abc"
}
function bar(){
    return 123
}
let flag=true
//unknown 只能赋值给anyunknown类型
//any类型可以赋值给任意类型
let result:unknown //最好不要使用any
if(flag){
    result = foo()
}else{
    result = bar()
}

void类型(函数没有返回值,一般不写)

function sum(num1:number,num2:number):void{
  console.log(num1+num2)
  return null
}
sum(20,30)

never类型(表示永远不会发生值的类型) 可以为了编写时添加必要的代码

function foo():never{
    //死循环
  while(true){

  }
  //抛出异常
  throw new Error()
}

image.png 运行会报错 让开发者添加更完善的代码

tuple类型(元组类型)

//tuple元组:多种元素的组合

// 数组的弊端
const info:any[]=["ddd",18,1.65] // 把多个不相同的元素放在数组

const name1 = info[0] //是any类型
console.log(name1.length);//不安全会报错

//元组的特点
const info1:[string,number]=["abc",1.88]
const name = info[0].length

export{}

函数的类型

1.函数作为参数时 fn:()=>void 2.定义常量时 编写函数的类型

type AddFnType = (num1:number,num2:number)=>number
const add:AddFnType  = (num1:number,num2:number){
    return num1+num2
}

参数的默认值

 function num (num:number=20,y:number){
 }
 num(undefined,30)
 //最好按照顺序写

函数的剩余参数...

function sum (...nums:number[]){
}
//会把传进来的值放nums:[20,30,40]
sum(20,30,40) 

函数的返回值类型

一般不需要写 会自动推导 看个人喜好 function num(num1:number,num2:number){ return num1+num2 }

匿名函数的参数类型 可以不写类型 会根据上下文来推导出来

image.png

对象类型

//point x/y 是对象类型
function printPoint(point:{x:number,y:number}){
    console.log(point.x);
}
printPoint({x:123,y:456})

可选类型

z?:number 注意:可选类型必须要跟在必选类型后面 比如function num(nunm1:number,y?:number)

//point x/y 是对象类型 z是可选类型 多个?
function printPoint(point:{x:number,y:number,z?:number}){
    console.log(point.x);
    console.log(point.z);
}
printPoint({x:123,y:456})
printPoint({x:123,y:456,z:111})

联合类型(Union Type)

定义:由两个或者多个其他类型组成的类型 表示可以是这些类型中的任何一个值 每一个类型被称为联合成员

//id是联合类型了 
function printD(id :number | string){

}
printD(123)
printD("abc")

联合类型使用 有时候要区分类型

 if(typeof id === 'string'){
      //typeof帮助确定id一定是string类型
      console.log(id.toUpperCase());
  }

可选类型和联合类型的关系

参数是可选类型时 它类似于这个参数值是 类型|undefined 的联合类型

//让一个类型本身是可选的
//参数是可选类型时 它类似于这个参数值是 类型|undefined 的联合类型
//function foo(message:string|}undifined)
function foo (message?:string){

}
foo(undefined)

类型别名

//type 用于定义类型别名
type IdType = string | number | boolean
type PointType={
    x:number,
    y:number,
    z?:number,
}
function printId (id:IdType){

}
function printPoint(point:PointType){
    
}

类型补充

类型断言 as

typescript无法获取具体的元素类型 可以转为具体或者不太具体(any/unknow)类型 把宽泛的类型转为具体的类型

//本来是HTMLElement类型 断言为HTMLImageElement
const e1 = document.getElementById("ddd") as HTMLImageElement
el.src = "url地址"

非空类型断言!

message! 保证message一定有值

 function foo1 (message?:string){
    //  if(message){ //判断是有值才会调用
    //     console.log(message.length);
    //  }
    console.log(message!.length);//保证message一定有值
   }

可选链的使用?.

属于javascript的知识 当对象属性不存在的时候 会短路 返回undifined

   console.log(info.friend?.name);//没值返回undefined

??和!!的作用

!!把类型转为boolean类型 ?? 空值合并操作符 是一个逻辑操作符 当操作符左边是null或者undefined时 返回右边的 const content = message ?? "你好"

字面量类型

image.png 字面量类型的意义是要结合联合类型

   let align:'left' | 'right' | 'center' = 'left'

字面量推理

image.png