快速学习Typescript基础知识

189 阅读2分钟
  1. 原始类型

1.string 2.number 3.null 4.boolean 5.undefined 6.symbol
    const a: string = '123'
    const b: number = 123
    const c:boolean = false
    const d:null = null
    const e:undefined = undefined
    const f:Symbol = Symbol()
  1. object类型

1.object对象 2.Array数组 3.function
    //object类型不单值对象 他是除了原始类型的所有类型
    
    const nfc1: object = ()=>{}      // 可以是函数
    const nfc2: object =  new Array  //可以数组
    const nfc3: object =  new Object //可以是对象
  1. 为对象限制类型

    //1.直接限制每一个参数
    const obj1: { name: string,id: number } = { name:'张三',id:1 }
    //2.使用接口限制  下面单独讲
  1. 为数组限制类型

    //1.使用Array泛型
    const arr1: Array<number> = [1,2,3]  //数组中的每一项只能为数字
    const arr2: number[] = [1,2,3]       //同上
    //2.元祖类型
    const arr3: [number,string,boolean] = [1,'2',true]
  1. 枚举类型

enum DataStatus{
    status1 = 1,
    status2 = 2,
    status3 = 3
}
const data = {
  name:'李四',
  id:0,
  status:DataStatus.status1
}
  1. 函数类型

    //1.函数声明类型约束
    function fn1(a: number,b: string): string{
        return a+'-'+b  //返回值必须为string
    }
    fn1(1,'2')//形参和实参个数必须完全一致
    //如需可选参数  在形参后加?即可
    function fn2(a: number,b: string,c?: boolean): string{
        return a+'-'+b  //返回值必须为string
    }
    fn2(1,'2')//这里不传参数c也可以
    
    //2.函数表达式
    const fn3:(a: number,b: number)=>number = (a,b)=>{
      return a+b
    }
    fn3(1,2)
  1. 任意类型 any

    //使用 any可以为参数a设置为所有类型
    const fn3 = (a: any)=>{
      return a
    }
    fn3(1)
    fn3('1')
    fn3(false)
  1. 隐式类型推断

    //因为第一次为num赋值为number 那么ts为num类型推断为number 
    let num = 1
    num = 100  // 重新赋值num没问题
    num = '100'  // 赋值为字符串报错
  1. 类型断言

    const resolve = [ 100,200,300 ]
    const res = resolve.find(n=>n>1) //此时ts认为res的值有可能是number或者undefined
    const res1 = res as number  //此时我们保证res1的值一定是number
  1. 接口 interfaces

    //1.静态属性
    interface Todo{
      id: number,
      name: string,
      checked?: boolean //可选成员 
      readonly title?: string //这里为title限制为只读的 不可更改 
    }
    //直接定义对象
    const todo: Todo= { id:1,name:'哈哈' } //可以不传入checked
    todo.title = '标题' //因为此时title有readonly限制 此时更改会报错
    //作为参数
    const setTodos = (todo: Todo)=>{
      return todo
    }
    
    //2.动态属性
    interface Toos{
      [key:string]:string //限制对象key(key字段不是固定要求,可自定义)为string类型 值也为string类型
    }
    const toos: Toos = {}
    toos.name = 'hello'
    toos.sex = '男'
  1. 泛型

将定义时无法确认的类型 在使用时用参数进行传递
//T代表string U代表number
const getTodos = <T,U>(list: T[],num:U): T[] =>{
  return list
}
const res = getTodos<string,Number>(['1','2','3'],U)