typescript基础使用

  • 基础类型
  1. number string array boolean object never null undefined
    let a:string = '1231'
    
  2. enum枚举类
    • 接口给前端返回一个status字段
enum NamesStatus{
    ABNHY='start'
    NOABNHY = 'noStart'
}
  1. type interface
    type num = {
        a:number,
        b:string
    }
    interface Num{
        a:number;
        b:string;
    }
    
  2. 联合类型(|)和交叉类型(&):联合类型只能使用一种类型,交叉类型是多个类型的合并
interface my{
    age:number;
    name:string;
}
interface she{
    face:true
}
// param: my |she 代表单个类型,是她其中的一种类型
// param: my & she 代表类型的合并,参数这三种类型都存在
function a(param: my | she ){}
  1. typeof 操作符可以用来获取一个变量声明或对象的类型
    function toA(param:string): Array<string>{
        return [param]
    }
    // 也可以用来约束其他函数类型
    type Fn = typeof toA 
    
  2. keyof 操作符可以用来一个对象中的所有 key 值
     interface job{
         n:string;
         age:number;
     }
     type param = keyof job  // n | job
    
  3. in: 用来遍历枚举类型:一般用于对象属性(key)值的定义
       type keys = 'a' |'b'|'c';
       type n = {
           [key in keys]: string;
       }
    
  4. extends:继承类型
     interface len{
         length:number
     }
     function values<T extends len>(param:T):T{
         console.log(param.length)
         return param
     }
     value(3) // error
     value('3')
     value({length:1, value:2})
    
  5. Paritial: Paritial将某个类型的属性变成可选类型?
       interface Part{
           age:number;
           name:string
       }
       type A = Paritial<Part>
    
  6. Record: Record<K extends keyof any, T>,将k中所有的属性值,转化为T类型
interface PI{
    title:string
}
type p = 'home' | 'a' | 'b'
interface B:Record<p, PI> = {

}
  1. Exclude: Exclude<T, U>将某个类型属于某个类型进行移除掉
const a = Exclude<'1'|'2'|'3', '2'|'3'>; // 将'1'类型进行移除
const b = Exclude<'1'|'2'|"4", "2">; // 将‘1’和‘4’进行移除
  1. Extract: Extract<T, U>:取交集
    const a = Extract<'a'|'b'|'c', 'a'|'c'>; // 'a'|'c'
    // 没有的交集,never
    const b = Extract<string|number|(()=>void), Function> // (()=>void)
  1. Pick:Pick<u, t>:挑选出类型中某一个类型
  2. Omit:Omit<U, T>:排除类型中某一个类型
  3. 相关面试题:
  • ts的好处:
    • js的超集,增加了可选静态类和面向对象编程,扩展js的语法;ts功能目前只多不少;
    • ts是纯面向对象编程,定义类和接口的概念
    • ts在开发阶段,编译就能出现代码中的错误;js需要运行才会暴露错误
    • 作为强类型语言,可以明确定义数据的类型,具有很好的可读性
    • ts有很多比较优秀特性;比如可选链
  • type和interface的异同:
    • interface描述数据结构, type描述类型
    1. 都支持描述一个对象或函数
    2. 都允许扩展extends:interfacetype可以相互extends
    3. type:可以申明基本类型别名,联合类型,元组类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值