• 一些 typescript 问答


    const vs readonly

    const 用于修饰变量,readonly 用于变量的属性

    const x: boolean;
    
    const x: {
        readonly a: boolean;
    } = {
        a: true;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    对于数组,const 只能保证地址不改动,ReadonlyArray则可以直接禁用 push/pop

    never vs unknown vs null vs undefined

    1. never 代表永远不会发生的类型,一般是被自动分配的,当然也可以自己给变量做类型注释
    function f1() {
      while (true) {}
    }
    
    function f2() {
      throw new Error('error');
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    f1f2都是永远返回不了的,称它们的返回值类型为是 never

    1. unknown 不知道是啥类型,但是肯定不是已知的类型,这是它和 any 最大的不同
    let vAny: any = 10; // ok
    let vUnknown: unknown = 10; // ok
    
    let s1: string = vAny; // ok
    let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. undefined 是未定义,null 是空

    enum vs const enum

    常量枚举经过编译器编译就是一个数字(0),单纯的 enum 会保留对象(Color.Red),所以常量枚举性能更好

    btw,默认 enum 转 number 是 0,1,2…
    但是如果指定其中的一个值,后面的会跟着列出来

    enum Colors {
      Red,
      Blue = 5,
      Yellow,
    }
    console.log(Colors.Red); // 0
    console.log(Colors.Blue); // 5
    console.log(Colors.Yellow); // 6
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    enum 支持反向映射

    console.log(Colors.Red); // 0
    console.log(Colors[0]); // Red
    
    • 1
    • 2

    type vs interface

    1. type 可作为基本类型的别名
    2. type 可声明 union type Pet = Dog | Cat
    3. type 可声明元组类型(tuple) type PetList = [Dog, Pet]
    4. interface 能够声明合并
    interface A {
      a: string;
    }
    
    interface A {
      b: number;
    }
    
    // A 为 {
    //   a: string;
    //   b: number;
    // }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    c++的引用和指针
    HttpURLConnection 接收长字符串时出现中文乱码出现问号��
    Redis学习笔记:Jedis
    快门图像传感器技术
    学习vue生命周期心得
    02-docker network
    excel公式怎么完全复制到另一列?
    Iptables防火墙limit模块扩展匹配规则
    关于android按钮颜色修改不了的原因
    iwebsec靶场 SQL注入漏洞通关笔记10- 双重url编码绕过
  • 原文地址:https://blog.csdn.net/weixin_43544179/article/details/126876623