Skip to content

Support TypeScript 4.5 #148

@mheob

Description

@mheob

TypeScript 4.5 is released.

With this, there are some new features around the imports.

Currently, they are not support by vsc-sort-imports and break the code.


For Example, some necessary changes from the TypeScript Docs:

type Modifiers on Import Names

// Which of these is a value that should be preserved? tsc knows, but `ts.transpileModule`,
// ts-loader, esbuild, etc. don't, so `isolatedModules` issues an error.
import { someFunc, BaseType } from "./some-module.js";
//                 ^^^^^^^^
// Error: 'BaseType' is a type and must be imported using a type-only import
// when 'preserveValueImports' and 'isolatedModules' are both enabled.

When these options are combined, we need a way to signal when an import can be legitimately dropped. TypeScript already has something for this with import type:

import type { BaseType } from "./some-module.js";
import { someFunc } from "./some-module.js";
export class Thing implements BaseType {
  // ...
}

This works, but it would be nice to avoid two import statements for the same module. That’s part of why TypeScript 4.5 allows a type modifier on individual named imports so that you can mix and match as needed.

import { someFunc, type BaseType } from "./some-module.js";
export class Thing implements BaseType {
    someMethod() {
        someFunc();
    }
}

In the above example, BaseType is always guaranteed to be erased and someFunc will be preserved under preserveValueImports, leaving us with the following code:

import { someFunc } from "./some-module.js";
export class Thing {
  someMethod() {
    someFunc();
  }
}

Import Assertions

TypeScript 4.5 supports an ECMAScript proposal for import assertions. This is a syntax used by runtimes to make sure that an import has an expected format.v

import obj from "./something.json" assert { type: "json" };

The contents of these assertions are not checked by TypeScript since they’re host-specific, and are simply left alone so that browsers and runtimes can handle them (and possibly error).

// TypeScript is fine with this.
// But your browser? Probably not.
import obj from "./something.json" assert {
    type: "fluffy bunny"
};

Dynamic import() calls can also use import assertions through a second argument.

const obj = await import("./something.json", {
  assert: { type: "json" },
});

The expected type of that second argument is defined by a new type called ImportCallOptions, and currently only accepts an assert property.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions