首页 > 其他分享 >TypeScript 4.9 发布,新增 satisfies 操作符

TypeScript 4.9 发布,新增 satisfies 操作符

时间:2022-11-18 18:35:02浏览次数:64  
标签:TypeScript name 4.9 NaN green satisfies red

TypeScript 4.9 发布,新增 satisfies 操作符

来源: OSCHINA 编辑: 罗奇奇 2022-11-17 07:04:50  1

TypeScript 4.9 已正式发布,此版本引入了多项新功能。

此版本的新内容:

下面详细介绍一下部分新功能:

新增 satisfies 操作符

TypeScript 开发者可能遇到的一个问题:既要确保表达式匹配某些类型,又要保留该表达式的具体类型。举例:

// Each property can be a string or an RGB tuple.
const palette = {
    red: [255, 0, 0],
    green: "#00ff00",
    bleu: [0, 0, 255]
//  ^^^^ sacrebleu - we've made a typo!
};

// We want to be able to use array methods on 'red'...
const redComponent = palette.red.at(0);

// or string methods on 'green'...
const greenNormalized = palette.green.toUpperCase();

可以看到, blue 错写成了 bleu,这里可以尝试通过在 palette 上使用类型注释来捕捉 bleu 拼写错误,但会丢失每个属性的信息。

type Colors = "red" | "green" | "blue";

type RGB = [red: number, green: number, blue: number];

const palette: Record<Colors, string | RGB> = {
    red: [255, 0, 0],
    green: "#00ff00",
    bleu: [0, 0, 255]
//  ~~~~ The typo is now correctly detected
};

// But we now have an undesirable error here - 'palette.red' "could" be a string.
const redComponent = palette.red.at(0);

新的 satisfies 操作符可以验证表达式的类型是否匹配某种类型,而不更改该表达式的结果类型。例如,可以使用 satisfies 来验证 palette 的所有属性是否与 string | number [] 兼容:

type Colors = "red" | "green" | "blue";

type RGB = [red: number, green: number, blue: number];

const palette = {
    red: [255, 0, 0],
    green: "#00ff00",
    bleu: [0, 0, 255]
//  ~~~~ The typo is now caught!
} satisfies Record<Colors, string | RGB>;

// Both of these methods are still accessible!
const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();

satisfies 可以用来捕获很多潜在的错误,例如确保一个对象具有某种类型的所有键:

type Colors = "red" | "green" | "blue";

// Ensure that we have exactly the keys from 'Colors'.
const favoriteColors = {
    "red": "yes",
    "green": false,
    "blue": "kinda",
    "platypus": false
//  ~~~~~~~~~~ error - "platypus" was never listed in 'Colors'.
} satisfies Record<Colors, unknown>;

// All the information about the 'red', 'green', and 'blue' properties are retained.
const g: boolean = favoriteColors.green;

更多 satisfies 示例,可以查看提出此问题实现该运算符的 PR 

类中的自动访问器

TypeScript 4.9 支持 ECMAScript 中即将推出的功能,称为自动访问器,自动访问器的声明就像类的属性一样,只是它们用 accessor 关键字声明。

class Person {
    accessor name: string;

    constructor(name: string) {
        this.name = name;
    }
}

自动访问器会转化为具有无法访问的私有属性的获取和设置访问器。

class Person {
    #__name: string;

    get name() {
        return this.#__name;
    }
    set name(value: string) {
        this.#__name = name;
    }

    constructor(name: string) {
        this.name = name;
    }
}

阅读关于该功能的 original PR 。

与 NaN 直接比较时报错

Javascrpit 的 NaN 是一个特殊的数值,代表 “不是数字”, NaN 不等于任何值 —— 即使是它本身。

console.log(NaN == 0)  // false
console.log(NaN === 0) // false
console.log(NaN == NaN)  // false
console.log(NaN === NaN) // false

这不是特定于 JavaScript 的问题,任何包含 IEEE-754 浮点数的语言都是如此。但是 JavaScript 的主要数字类型是浮点数,很多场景都需要检查 NaN,而正确​​的方法是使用 Number.isNaN 来检查 NaN 类型。

但问题来了,很多新手都会习惯性使用 someValue === NaN 进行检查。因此 TypeScript 4.9 引入了更严格的警告:与 NaN 直接比较时会报错,并且会建议使用 Number.isNaN 的一些变体。

function validate(someValue: number) {
    return someValue !== NaN;
    //     ~~~~~~~~~~~~~~~~~
    // error: This condition will always return 'true'.
    //        Did you mean '!Number.isNaN(someValue)'?
}

File-Watching 使用文件系统事件

在早期版本中,TypeScript 严重依赖轮询来查看单个文件。在 TypeScript 4.9 中,文件监视默认由文件系统事件提供支持,只有在未能设置基于事件的监视程序时才会回退到轮询。

对于大多数开发人员来说,当以 --watch 模式运行或使用 TypeScript 支持的编辑器(如 Visual Studio 或 VS Code)运行时,会提供更好性能体验。

可以在 GitHub 上阅读有关此更改的更多信息。

引入 “删除未使用的导入” 命令

以前,TypeScript 只支持两个编辑器命令来管理导入:

import { Zebra, Moose, HoneyBadger } from "./zoo";
import { foo, bar } from "./helper";

let x: Moose | HoneyBadger = foo();

第一个称为 “组织导入 -Organize Imports”,它会删除未使用的导入,然后对剩余的进行排序。但它会重写文件,使其看起来像这样: 

import { foo } from "./helper";
import { HoneyBadger, Moose } from "./zoo";

let x: Moose | HoneyBadger = foo();

TypeScript 4.3  引入了一个名为 “Sort Imports” 的命令,它只会对文件中的导入进行排序,但不会删除导入,它会像这样重写文件:

import { bar, foo } from "./helper";
import { HoneyBadger, Moose, Zebra } from "./zoo";

let x: Moose | HoneyBadger = foo();

TypeScript 4.9  提供了 “删除未使用的导入 - Remove Unused Imports” 功能命令,该功能将删除未使用的导入名称和语句,但会单独保留其相对顺序。

import { Moose, HoneyBadger } from "./zoo";
import { foo } from "./helper";

let x: Moose | HoneyBadger = foo();

可以在此处查看该功能的详细信息

return 关键字的 go-to-definition 功能

在 return 关键字上运行 go-to-definition 时,TypeScript 现在会跳转到相应函数的顶部,有助于快速了解  return 属于哪个函数。

TypeScript 会将此功能扩展到更多关键字,例如 await 和 yield 或 switch、case 和 default。

查看该功能的原始 PR 了解更多信息。

 

其余性能优化和 Bug Fixed 等细项可以在发布公告中查阅。

可以通过 NuGet 获取新版本,或者使用 npm,通过以下命令 :

npm install -D typescript

标签:TypeScript,name,4.9,NaN,green,satisfies,red
From: https://www.cnblogs.com/sexintercourse/p/16904190.html

相关文章

  • [Typescript] noImplicitOverride
    Let'ssayyouextendsfromabaseclass,youintenttooverrideamethodinbaseclassclassBaseCmp{showCmp(){}hideCmp(){}helperMethod(){}}cla......
  • 【草稿】在 Typescript 中从对象中动态解构接口类型
    问题interfaceA{title:string,description:string,}leta={title:"titlea",description:"descriptiona",url:"http://example.com/a"}是......
  • React中常见的TypeScript定义实战
    一引沿Fiber架构是React16中引入的新概念,目的就是解决大型React应用卡顿,React在遍历更新每一个节点的时候都不是用的真实DOM,都是采用虚拟DOM,所以可以理解成fiber就是R......
  • React-hooks+TypeScript最佳实战
    ReactHooks什么是HooksReact一直都提倡使用函数组件,但是有时候需要使用state或者其他一些功能时,只能使用类组件,因为函数组件没有实例,没有生命周期函数,只有类组件才......
  • 自学 TypeScript 第三天 使用webpack打包 TS 代码
    前言:大家好啊,昨天介绍了TS编译器的配置,但在我们实际开发当中直接使用TS编译器去编译代码的情况会有,但没有很多,因为我们在开发大型项目的时候,一般我们都会用到打包工具......
  • 这10个TypeScript高级技巧,助你成为更好的开发者!
    在使用了一段时间的Typescript之后,我深深地感受到了Typescript在大中型项目中的必要性。可以提前避免很多编译期的bug,比如烦人的拼写问题。并且越来越多的包都在使用TS,所以......
  • [Typescript] Variable assignment - extends infer X
    Youcanuse`extendsinferX`toassigntheresultofanexpressiontoavariabletypeSomeFunction<U>=SuperHeavyComputation<U>extendsinferResult......
  • 自学 TypeScript 第二天 编译选项
    前言:昨天我们学习了TS的数据类型,不知道大家回去以后练习没练习,如果你练习了一定会发现一个问题,我们的TS好像和JS不太一样JS写完之后直接就可以放到页面上,就可以用......
  • NOTE_vanilla+typescript
    E:\song\threejs_learn\vite-project\index.html<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><linkrel="icon"type="image/svg+xml"......
  • [Typescript]106. Medium - OnPropChnagedMethods
    typeOnPropChnagedMethods<T>={[KeyinkeyofT&stringas`${Key}Changed`]:(cb:(newValue:T[Key])=>void)=>void}declarefunctionmakeWatchedObject<......