laitimes

TypeScript 5.3 first look, do you have the features you want?

author:CSDN
TypeScript 5.3 first look, do you have the features you want?

CSDN Editor's Note: Which of these features you would most like to implement in this article.

Original link: https://www.totaltypescript.com/typescript-5-3

Author | Translated by Matt Pocock ChatGPT Editor-in-Charge | Produced by Mengyidan | CSDN(ID:CSDNnews)

On August 24, Daniel Rosenwasser, Senior Project Manager of TypeScript, released TypeScript version 5.2 on Guanbo, which has made several feature updates, added support for the upcoming explicit resource management feature in ECMAScript, and introduced Decorator Metadata, which allows decorators to easily create and use metadata on any class they use. Named and anonymous tuple elements, Tuple type support for each element with optional tags or names, etc.

At the same time, the official team also announced the TypeScript 5.3 iteration plan, which is used to plan the features that the 5.3 version may include, and the author summarizes some of the features that developers are most interested in. Let's take a look.

TypeScript 5.3 first look, do you have the features you want?
TypeScript 5.3 first look, do you have the features you want?

Import Attributes

TypeScript 5.3 is likely to add import properties, which are already in line with Stage 3's TC39 proposal. This feature allows developers to import specified options, for example, you can specify the JSON import type:

import json from './foo.json' with { type: 'json' };           

It also allows you to specify the type of dynamic import:

import("foo.json", { with: { type: "json" } });           

You can also re-export a module with a validated type:

export { val } from './foo.js' with { type: "javascript" };           

Or instantiate the worker with a validated type:

new Worker("foo.wasm", {              type: "module",              with: { type: "webassembly" },              });           

The primary purpose of adding this feature is for security reasons, to prevent the response server from accidentally serving different MIME types, resulting in unexpected code execution.

TypeScript 5.3 first look, do you have the features you want?

Throw exceptions are supported

The throw expression is a syntax in JavaScript that is a way to throw an exception without using a statement, and can be written as:

const id = searchParams.id || throw new Error("id is required");           

This is not available in JavaScript and throws an error in TypeScript:

const id = searchParams.id || throw new Error("id is required");           
Expression expected.

However, throw expressions are unlikely to be implemented in TypeScript 5.3. The proposal is still in Phase 2, some way from the Phase 3 required to add to TypeScript.

But the TypeScript iteration program in particular added "support" for the proposal. This means that they are actively working on it, so it is possible that it will be implemented in future JavaScript/TypeScript versions.

TypeScript 5.3 first look, do you have the features you want?

Isolated Declarations

In a single codebase with many packages, you may encounter interdependencies. In this case, you might end up with a very deep, "family tree" structure, where package A depends on package B, package B depends on package C, and so on.

In this case, TypeScript's inspection may become very slow. First you have to check the D package, then the C package, the B package, and finally the A package.

The reason for this is that TypeScript itself needs to print the declaration file (.d.ts file) for each package, which also means that they are type-checked, which is slow.

One way to speed it up is to have faster tools such as esbuild or swc create declaration files for each package. But at the moment this is not possible. TypeScript doesn't have strict requirements for how many comments need to be added to the code. Third-party tools cannot generate claims files based on inference.

Introducing quarantine declarations - This is a new, stricter pattern of TypeScript that addresses this issue.

You can add an option at tsconfig.json:

{              "compilerOptions": {              "isolatedDeclarations": true              }              }           

Once enabled, it requires developers to add comments strictly, and exactly how to do so is still under discussion and may change over time. As a demo, the return type annotations of exported functions are likely mandatory to avoid TypeScript needing to infer them.

Developers only need to enable isolatedDeclarations on the shared package - you don't need to enable it on the application code. Restricting shared packages may be desirable, as developers will typically want to add more comments to shared packages.

Generic functions narrow down

One piece of advice I give when dealing with generic functions is "don't be afraid to use as". Current TypeScript does not perform well in terms of reduced typing inside generic functions.

For example:

TypeScript 5.3 first look, do you have the features you want?

The above code is trying to return a value from an object based on key. If 'foo' is passed in, a string will be returned. If 'bar' is passed in, a number is returned.

The code looks fine, but TypeScript reports an error.

The reason is that TypeScript does not narrow Example[T] to the correct key, and once Example[T] is minified, it will cause it to be typed as never, so an error is reported.

Currently, the only way to make this segment work is to enter it as "never".

function exampleFunc<T extends keyof Example>(              key: T              ): Example[T] {              if (key === "foo") {              return "abc" as never;              } else {              return 123 as never;              }              }           

It feels really bad.

TypeScript 5.3 may make some changes here. There is a long-open issue that mentions the motivation for this change.

This is a very happy thing for me. Generic errors here are not easy to infer for developers, and if TypeScript becomes smarter under such errors, it will be easier for developers to use generics.

TypeScript 5.3 first look, do you have the features you want?

String autocompletion

There is a famous string completion technique in TypeScript, which is to use string&{} to achieve automatic loose completion:

type IconSize =              | "small"              | "medium"              | "large"              | (string & {});           

The comment may seem strange, but the reason it exists is so that you can pass any value to IconSize while also getting auto-completion of the other three values.

const icons: IconSize[] = [              "small",              "medium",              "large",              "extra-large",              "anything-goes",              ];           

TypeScript 5.3 may introduce a new feature that makes this hack unnecessary. Developers will be able to use strings as types and get the same autocompletion.

type IconSize =              | "small"              | "medium"              | "large"              | string;           

This will be very popular – especially since Webstorm users have been owning it for years.

TypeScript 5.3 first look, do you have the features you want?

fetch in @types/node

On February 1, 2022, the Node.js team merged a pull request to add the Fetch API to Node.js. This means that Node.js will have a fetch function like a browser. However, this feature has not yet been added to @types/node, and the issue is currently hotly discussed under the DefinitelyTyped section.