jeanpaul62
jeanpaul62

Reputation: 10571

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?

Upvotes: 5

Views: 1463

Answers (2)

l7412471
l7412471

Reputation: 31

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

Upvotes: 3

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249716

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. If you want to ensure the un-assignablity of number to A you need to use branded types.

type A = number & { isA: undefined};

declare function f(): A;

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

play

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.

Upvotes: 3

Related Questions