Typescript 类型别名让 Intellisense 显示别名,而不是源类型

Typescript type alias let Intellisense show alias name, not source type

考虑这段简短的代码

type A = number;

declare function f(): A;

const a = f(); // `a` is number, not A

为什么 TS 显示 a: number 而不是 a: A

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

也不是说 Anumber 实际上是同一类型。如果要确保 number 不可分配给 A,则需要使用

type A = number & { isA: undefined};

declare function f(): A;

const a = f(); // `a` is A, not number

play

注意:还有一项提议 (this and this) 将品牌类型机制融入打字稿,但在撰写本文时尚未最终确定。