TypeScript 4的新增功能

Before heading into the article, I want to say congratulations, TypeScript!

在进入本文之前,我要先祝贺您,TypeScript!

The new version of TypeScript was released a few days ago. There are quite a number of interesting features. In this article, I’ll give you some brief information about what’s been changed. (If you want to see the details, check this development note out.)

新版本的TypeScript是几天前发布的。 有很多有趣的功能。 在本文中,我将向您简要介绍已更改的内容。 (如果您想查看详细信息,请查看此开发说明 。)

免责声明 (Disclaimer)

TypeScript 4 isn’t the stable version yet; it’s a beta. So you should make sure you’re really OK to use this version in your production codes since beta means they could change some features before the final release.

TypeScript 4尚未稳定。 这是一个测试版。 因此,您应该确保可以在生产代码中使用此版本,因为Beta意味着它们可以在最终版本之前更改某些功能。

可变参数元组类型 (Variadic Tuple Types)

Let’s say we have the function concat written on our TS 3.9 base.

假设我们在TS 3.9的基础上编写了concat函数。

TS 3 (TS 3)

/** TS 3 */


function concat(arr1: T, arr2: U) {
  return [...arr1, ...arr2];
}


const names = ['John', 'Sarah'];
const genders = ['Male', 'Female'];
const scores = [100, 60];


// r1 is any[] type
const r1 = concat(names, scores);


// r2 is string[] type
const r2 = concat(names, genders) as string[];


// r3 is (string | number)[] type
const r3 = concat(scores, genders) as (string | number)[];

The function takes two parameters that each type extends any[]. Take a look at the three results from calling the function.

该函数有两个参数,每种类型都扩展了any[] 。 看一下调用该函数的三个结果。

r1 type is any[], though it’s the result from the function taking string[] and number[] type values because the function concat can’t infer the return type using T and U.

r1类型是any[] ,尽管它是函数采用string[]number[]类型值的结果,因为函数concat无法使用TU推断返回类型。

So we had to cast the return type manually as r2 and r3 did. Even though there might be some kind of solution for this case in TS 3.x, we really just needed something cool so we don’t have to think about this.

因此,我们必须像r2r3一样手动转换返回类型。 即使在TS 3.x中针对这种情况可能有某种解决方案,我们确实只是需要一些很棒的东西,所以我们不必考虑这一点。

In TS 4, what you can do now is to spread the types like below.

在TS 4中,您现在可以做的就是扩展如下类型。

/** TS 4 */


type ArrNum = number[];
type ArrStr = string[];
// (string | number)[]
type Spread = [...ArrNum, ...ArrStr];


type Strings = [string, string];
type Numbers = [number, number];
// [string, string, number, number]
type StrStrNumNum = [...Strings, ...Numbers];


// [string, string, ...Array]
type Unbounded = [...Strings, ...ArrNum, boolean];
  
// [string, string, number, number, boolean]
type Unbounded2 = [...Strings, ...Numbers, boolean];
type Spread = [...ArrNum, ...ArrStr];

If a type consists of some types with unknown length, TS 4 will treat them as an array of a type.

如果类型由长度未知的某些类型组成,则TS 4会将它们视为类型的数组。

type StrStrNumNum = [...Strings, ...Numbers];

Otherwise, TS 4 can count how many of the same types are in each type so it can spread them into the new type.

否则,TS 4可以计算每种类型中有多少个相同类型,以便可以将它们扩展为新类型。

TS 4 (TS 4)

/** TS 4 */


function concat(arr1: T, arr2: U): [...T, ...U] {
  return [...arr1, ...arr2];
}


const names = ['John', 'Sarah'];
const genders = ['Male', 'Female'];
const scores = [100, 60];


// r1 is (string | number)[] type
const r1 = concat(names, scores);


// r2 is string[] type
const r2 = concat(names, genders);


// r3 is (string | number)[] type
const r3 = concat(scores, genders);

All we need in TS 4 now is to declare the return type of the function as […T, …U]; then we don’t have to cast the result every time. Plus, now the r1 also has the right type instead of any[].

现在,在TS 4中,我们需要将函数的返回类型声明为[…T, …U] ; 那么我们不必每次都强制转换结果。 另外,现在r1也具有正确的类型,而不是any[]

You can check out more details about this here.

您可以在此处查看有关此内容的更多详细信息。

标记的元组元素 (Labeled Tuple Elements)

With the type keyword in TS 4, now you can tell TS each type of the arguments you pass into the function.

使用TS 4中的type关键字,现在您可以告诉TS传递给函数的每种参数类型。

TS 3 (TS 3)

/** TS 3 */


function foo(x: [string, number]) {
  // a is string type
  // b is number type
  const [a, b] = x;
}

TS 4 (TS 4)

/** TS 4 */


function foo(x: [first: string, second: number]) {
  // a is string type
  // b is number type
  const [a, b] = x;
}

You might not see the big difference between them; the TypeScript team introduced this feature for better readability. And when you want to express the rest of the arguments, you could write your type like:

您可能看不到它们之间的巨大差异。 TypeScript团队引入了此功能,以提高可读性。 而且,当您想表达其余参数时,可以这样写:

type Foo = [first: string, second: number, ...rest: any[]];

One thing to remember is that if you give a label to the types, you must give a label to all of the types, like this:

要记住的一件事是,如果给类型赋予标签,则必须为所有类型赋予标签,如下所示:

// Error
type Bar = [first: string, number];// It works
type Baz = [first: string, second: number;

You can check out more details about this here.

您可以在此处查看有关此内容的更多详细信息。

构造函数的类属性推断 (Class Property Inference From Constructors)

In the TS 3 base, your class-member properties must have a specific type, unless you don’t turn off thenoImplicitAny option.

在TS 3基础中,您的类成员属性必须具有特定的类型,除非您不关闭noImplicitAny选项。

/** TS 3 */


class Student {
  // age is any type
  age;
//~~~
// ^- Error
  
  construtor() {
    this.age = 10; 
  }
  
  // return type is any
  getDoubleAge() {
    return this.age * 2; 
  }
}

Otherwise, the property age of the class Student gives you an error that it has an any type implicitly. And the return type of getDoubleAge is also an any because the age is any type.

否则, Student类的属性age会给您一个错误,即它隐式具有any类型。 而且getDoubleAge的返回类型也是any因为ageany类型。

In TS 4, it can infer the type more naturally by how the property is initialized in the constructor.

在TS 4中,它可以通过如何在构造函数中初始化属性来更自然地推断类型。

/** TS 4 */


class Student {
  // age is number type
  age;
  
  construtor() {
    this.age = 10; 
  }
  
  // return type is number
  getDoubleAge() {
    return this.age * 2; 
  }
}

One thing to remember is that since TS 4 checks the member property type from the constructor, you should always make sure that you don’t confuse TypeScript.

要记住的一件事是,由于TS 4从构造函数中检查成员属性类型,因此应始终确保不要混淆TypeScript。

/** TS 4 */


class Student {
  // age is string | number type
  age;
  
  construtor() {
    if (Math.random() > 0.5) {
      this.age = 10;
    } else {
      this.age = '20';
    }
  }
  
  // Error
  // Because TS doesn't know
  // if it should treat the property
  // as a string or a number
  getDoubleAge() {
    return this.age * 2;    
         //~~~~~~~~
         // ^- Error
  }
}

Check out the figure above. TS doesn’t know which type the age should be considered.

查看上图。 TS不知道应考虑哪种age

You can check out more details about this here.

您可以在此处查看有关此内容的更多详细信息。

短路分配运算符 (Short-Circuiting Assignment Operators)

A very simple comparison. Now you can do this in TS 4.

一个非常简单的比较。 现在,您可以在TS 4中执行此操作。

/** TS 3 */


let a = 10;
let b = 20;
let c = 30;


// Error
// Not supported in TS 3
a &&= b;
a ||= b;
a ??= c;


// Supported in TS 3
a += b;
a -= b;
a *= b;
a /= b;
a **= b;
a <<= b;

The sign &&, ||, and ?? weren’t supported in TS 3 with = like in the above screenshot. But in TS 4, they’re supported.

标志&&||?? TS 3中不支持使用=如上面的屏幕截图所示。 但是在TS 4中,它们得到了支持。

/** TS 4 */


let a = 10;
let b = 20;
let c = 30;


// Now supported in TS 4
a &&= b;
a ||= b;
a ??= c;


// Supported in TS 4
a += b;
a -= b;
a *= b;
a /= b;
a **= b;
a <<= b;

So now you can do this with this feature:

现在,您可以使用以下功能执行此操作:

let values: string[];
// Before
(values ?? (values = [])).push("hello");
// After
(values ??= []).push("hello");

You can check out more details about this here.

您可以在此处查看有关此内容的更多详细信息。

'unknown' catch'子句绑定中的'unknown' ('unknown' on ‘catch' Clause Bindings)

Previously, one of the uncomfortable features in TS was that you couldn’t control the type of an error type in the catch clause.

以前,TS中不舒服的功能之一是您无法在catch子句中控制错误类型的类型。

/** TS 3 */


function error() {
  try {
    throw new Error();
  } catch (e: unknown) {
    //        ~~~~~~~~
    //               ^- Error in TS 3
    // Catch clause is any type
    // and it doesn't let you change the type
    console.log(e.toUpperCase());
  }
}

But in TS 4, it lets you change its type to unknown for better safety. But you can’t still change the type to the customed one.

但是在TS 4中,您可以将其类型更改为unknown以提高安全性。 但是您仍然无法将类型更改为自定义类型。

/** TS 4 */


function error() {
  try {
    throw new Error();
  } catch (e: unknown) {
    // e has to be either any or unknown in TS 4


    // Error
    // Object is of type unknown
    console.log(e.toUpperCase());
    //          ~~
  }
}

In the catch clause, you can change the type like below.

catch子句中,您可以更改以下类型。

if (typeof e === 'string') {
// It works now
console.log(e.toUpperCase());
}

You can check out more details about this here.

您可以在此处查看有关此内容的更多详细信息。

'@deprecated' ('@deprecated')

In TS 4, you can let the other developers know some methods are deprecated.

在TS 4中,您可以让其他开发人员知道不赞成使用某些方法。

/** TS 3 */


class Deprecated {
  /** @deprecated */
  static sayHi() {
    console.log('hi');
  }
}


// Nothing is wrong with this
Deprecated.sayHi();

Some JavaScript editor tools more visually let you know they’re deprecated. Of course, TS itself also lets you know that.

一些JavaScript编辑器工具可以更直观地让您知道它们已被弃用。 当然,TS本身也会让您知道这一点。

/** TS 4 */


class Deprecated {
  /** @deprecated */
  static sayHi() {
    console.log('hi');
  }
}


// TS tells you it is deprecated
Deprecated.sayHi();


/** @deprecated *
class ClassDeprecated {}


// TS tells you it is deprecated
new ClassDeprecated();

If you’re using VS Code for a JavaScript editor, then update it to the newest version and restart the program. VS Code will make you notice what’s deprecated more easily.

如果您将VS Code用于JavaScript编辑器,则将其更新到最新版本并重新启动程序。 VS Code将使您更容易注意到不推荐使用的内容。

In TS 4.0 base with VS Code 在带有VS Code的TS 4.0 base中

You can check out more details about this here.

您可以在此处查看有关此内容的更多详细信息。

结论 (Conclusion)

If you want to know about the new features further than what I introduced, you can always check them out here. It seems TS 4 doesn’t have so many big breaking changes and the currently introduced version is the beta, so we should keep track of its changes or bug fixes.

如果您想了解除我介绍的功能以外的其他新功能,可以随时在此处查看它们。 TS 4似乎没有太大的重大更改,并且当前引入的版本是beta,因此我们应该跟踪其更改或错误修复。

If you want to install this beta version, you can install it via npm or Yarn.

如果要安装此Beta版本,则可以通过npm或Yarn安装它。

npm i -D typescript@beta
yarn add -D typescript@beta

翻译自: https://medium.com/better-programming/whats-new-in-typescript-4-fe8d50f08e31

你可能感兴趣的:(python)