[英]Typescript type alias let Intellisense show alias name, not source type
Consider this short piece of code考虑这段简短的代码
type A = number;
declare function f(): A;
const a = f(); // `a` is number, not A
Why does TS show a: number
instead of a: A
?为什么 TS 显示
a: number
而不是a: A
?
Type aliases as their name suggests are just different names for another types.顾名思义,类型别名只是其他类型的不同名称。 Type alias names are not something the compiler is guaranteed to preserve (unlike interfaces) and it applies a heuristic that gives the best user experience (in this case it arguably fails).
类型别名不是编译器保证保留的东西(与接口不同),它应用启发式算法来提供最佳用户体验(在这种情况下它可能会失败)。
Also not that A
and number
are effectively the same type.也不是
A
和number
实际上是同一类型。 If you want to ensure the un-assignablity of number
to A
you need to use branded types .如果要确保
number
不可分配给A
,则需要使用brand types 。
type A = number & { isA: undefined};
declare function f(): A;
const a = f(); // `a` is A, not number
Note: There are also a proposals ( this and this ) to have the branded type mechanism baked into typescript but at the time of writing it is not yet finalized.注意:还有一个提案( this和this )将品牌类型机制融入 typescript 但在撰写本文时尚未最终确定。
Here's how you can preserve the alias name, while using it like a number这是保留别名的方法,同时像数字一样使用它
interface PreserveAliasName extends Number {}
type A = number & PreserveAliasName;
declare function f(): A;
const a = f(); // `a` is A
const b: A = 5; // allows primitive assign, unlike branded types
const c = BigInt(b); // still allows usage like primitive
Compared to branded type:与品牌类型相比:
type A = number & { __brand: 'A' };
declare function f(): A;
const a = f(); // `a` is A
const b: A = 5;
Type 'number' is not assignable to type '{ __brand: "A"; }'
const b: A = 5 as A; // needs casting
const c = BigInt(b); // still allows usage like primitive
Compared to interface与界面相比
interface A extends Number {}
declare function f(): A;
const a = f(); // `a` is A
const b: A = 5; // allows primitive assign
const c = BigInt(b)
Argument of type 'A' is not assignable to parameter of type 'string | number | bigint | boolean'.
const c = BigInt(b as number) // needs casting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.