When working with TypeScript, there are limitations on how types are displayed and represented in the code. Currently, TypeScript does not provide explicit control over whether types are shown as written or expanded to their definitions. An open feature request exists for improvement in this area (microsoft/TypeScript#45954), but it is not yet part of the language.
To work around this limitation, you can try to leverage the display heuristics of TypeScript. One approach is to manually define the type you want:
function printX(x: Blob | File) {
console.log(x);
}
If you want to ensure that the displayed type matches your expectations, you can introduce validation checks:
declare var __xTest: X;
declare var __xTest: Blob | File;
// ^^^^^^^
// Ensure consistency between declarations
Alternatively, using generics can prompt TypeScript to fully evaluate the type when calling a function like printX()
:
function printX<Y extends X & {}>(x: Y) {
console.log(x);
}
printX(
// ^ printX(x: Blob | File): void
Note the need to intersect X
with an empty object type to prevent re-evaluation as just
X</code. By creating meaningful type aliases, you can help maintain clarity in your code:</p>
<pre><code>type BlobOrFile = Blob | File;
function printX(x: BlobOrFile) {
console.log(x);
}
printX(
// ^ printX(x: BlobOrFile): void
While TypeScript's behavior may be limiting, making strategic choices in defining and naming types can enhance code readability and understanding.