代码之家  ›  专栏  ›  技术社区  ›  jeanpaul62

类型脚本类型别名允许Intellisense显示别名,而不是源类型

  •  0
  • jeanpaul62  · 技术社区  · 6 年前

    考虑一下这段代码

    type A = number;
    
    declare function f(): A;
    
    const a = f(); // `a` is number, not A
    

    为什么TS会出现 a: number 而不是 a: A ?

    0 回复  |  直到 6 年前
        1
  •  3
  •   Titian Cernicova-Dragomir    6 年前

    顾名思义,类型别名只是其他类型的不同名称。类型别名不是编译器保证保留的(与接口不同),它应用了一种启发式方法,可以提供最佳的用户体验(在这种情况下,它可能会失败)。

    也不是那样 A number 实际上是同一类型。如果你想确保 数字 A. 你需要使用 branded types .

    type A = number & { isA: undefined};
    
    declare function f(): A;
    
    const a = f(); // `a` is A, not number
    

    play

    注:还有一个建议( this this )将品牌打印机制烘焙到typescript中,但在编写时尚未完成。

    推荐文章