许 志强

许 志强

1656578280

如何在 TypeScript 中扩展枚举

TypeScript 受到开发者社区的喜爱有很多原因,其中之一是因为它为其中编写的代码提供了静态检查。

在开发生命周期的早期发现问题可以节省几天调试随机、模糊错误的时间,这些错误有时会在使用JavaScript 等动态语言时弹出。

TypeScript 可以帮助您的代码更可预测和更好地记录,使重构更容易,并帮助减少您在生产应用程序运行时可能遇到的潜在错误。它的受欢迎程度和力量体现在其 93% 的开发者满意度和在过去五年中飙升的使用率上。

对 TypeScript 至关重要的一种语言机制是枚举。 

TypeScript 中的枚举是什么?

有趣的是,枚举不是打字的特性,就像大多数 TypeScript 一样——事实上,它们是为数不多的增强语言的新特性之一。

枚举允许开发人员为变量定义一组严格的选项。例如:

enum Door {
  Open,
  Closed,
  Ajar // half open, half closed
}

枚举默认为数字枚举,所以上面的枚举本质上是一个以0, 1, 和2为键的对象,我们可以在转译的JavaScript 代码中看到。

"use strict";
var Door;
(function (Door) {
    Door[Door["Open"] = 0] = "Open";
    Door[Door["Closed"] = 1] = "Closed";
    Door[Door["Ajar"] = 2] = "Ajar"; // half open, half closed
})(Door || (Door = {}));
console.log(Door.FullyOpened);

在 TypeScript 中,您还可以使用字符串枚举,如下所示:

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}

如果您随后使用此Door枚举,则可以确保变量仅使用枚举中指定的三个选项。因此,您不能意外分配错误或以这种方式轻松创建错误。

如果您确实尝试使用另一个变量,它将引发如下类型错误:

 

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}
console.log(Door.FulyOpened)

Property 'FullyOpened' does not exist on type 'typeof Door'.

为什么我们需要扩展一个枚举?

扩展是面向对象的四大支柱之一,是 TypeScript 中存在的语言特性。扩展枚举允许您从本质上复制变量定义并添加一些额外的东西。

因此,例如,您可能正在尝试执行以下操作:

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}

enum DoorFrame extends Door { // This will not work!
  Missing = "noDoor"
}

console.log(DoorFrame.Missing)

然后,我们可以将额外的属性添加到枚举中,甚至将两个枚举合并在一起,以仍然对我们的枚举进行严格的键入,同时还可以在定义它们之后更改它们。

但请注意,上面的代码片段不起作用!它无法转换并引发四个不同的错误。

你能扩展枚举吗?

简短的回答是否定的,你不能扩展枚举,因为 TypeScript 没有提供扩展它们的语言功能。但是,您可以使用一些变通方法来实现继承。

TypeScript 中的类型交集

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}

enum DoorFrame {
  Missing = "noDoor"
}

type DoorState = Door | DoorFrame; 

在上面的代码块中,我们使用了一个交集类型。交集就像一个“或”,它只是意味着DoorState类型要么是 type 要么Door是 type DoorFrame

这现在意味着DoorState可以互换使用两个枚举中的任何一个变量。

传播语法

我们在之前的转译代码中已经看到,枚举变成了一个 JavaScript 对象,具有您的枚举指定的键和值。

在 TypeScript 中,如果我们愿意,我们可以编写纯 JavaScript。事实上,这是 TypeScript 的一大优势。例如,您可以将所有代码重命名file.jsfile.ts并关闭编译器对代码的检查。只要您运行编译/转换步骤,一切都会正常运行,代码更改为零。

我们可以通过知道当我们的枚举变成 JavaScript 时,它将是一个 JavaScript 对象字面量并使用扩展语法来利用它,如下所示

enum Move {
  LEFT = 'Left',
  RIGHT = 'Right',
  FORWARD = 'Forward',
  BACKWARD = 'Backward'
}
const myMove = {
  ...Move,
  JUMP: 'Jump'
}

但是,此解决方案已在第二次进行了描述,因为它不如交叉类型的解决方案好,因为它不如我们的第一个解决方案强大。这是因为枚举的“组合”发生在运行时,而当我们使用类型交集时,类型检查可以发生在编译/转译时,而不是运行时。

TypeScript 枚举最佳实践

我们已经讨论了如何在 Typescript 中扩展枚举,但枚举并不是解决所有问题的灵丹妙药。如果使用不当,枚举会使您的代码可读性、可伸缩性和可维护性更差,而不是改进您的代码。

因此,让我们介绍一些在 TypeScript 中使用枚举时使用的最佳实践和常见模式。

1. 避免异构枚举

我已经解释了我们如何拥有这样的字符串枚举:

enum Seasons {
  Summer = "Summer",
  Winter = "Winter",
  Spring = "Spring",
  Fall = "Fall"
}

除了有这样的数字枚举:

enum Decision {
  Yes,
  No
}

但是,还有第三种类型的枚举,您可能不知道,称为异构枚举。这是您可以在同一个枚举中使用字符串和数字枚举的地方。

文档中的一个示例是这样的:

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

重要的是要注意,即使是文档也不鼓励这种做法,因为在这种情况下,使用这种方法表明您可能需要:

  • 重新考虑这两个变量之间的关系
  • 创建两个单独的枚举
  • 使它们都符合一种数据类型

2. “枚举即配置”反模式

有时代码功能可能被迫遵守枚举选项,这很快就会变成反模式。

这是一个例子

enum Operators {
  Add,
  Subtract
}
function calculate(op: Operators, firstNumber: number, secondNumber: number) {
  switch(op) {
    case Operators.Add: return firstNumber + secondNumber
    case Operators.Subtract: return firstNumber - secondNumber
  }
} 

上面的代码看起来相当简单和安全,因为我们的例子确实是简单和安全的。

但是在大型代码库中,当您将实现细节严格绑定到这样的枚举类型时,可能会导致一些问题:

  • 您创建了两个事实来源(如果枚举更改,则枚举和函数都需要更新)
  • 这种模式将在代码周围传播元数据
  • 代码块不再是通用的

如果您需要执行上述操作,则更简单(更简洁)的模式可能如下所示。

const Operators = {

  Add: {
    id: 0,
    apply(firstNumber: number, secondNumber: number) { return firstNumber + secondNumber }
  },

  Subtract: {
    id: 1,
    apply(firstNumber: number, secondNumber: number) { return firstNumber - secondNumber }
  }
}

您可以在此处此处阅读有关此模式的更多信息。

3.枚举最能代表的数据类型

通常有一种方法可以将代码中使用的不同类型的数据组合在一起:离散变量或连续变量。

离散变量是在它们的表示之间有空格的数据,并且只有几个表示。这里有一些例子:

  • 一周中的日子
    • 星期一
    • 周二
    • 星期三
    • 星期四
    • 周五
    • 星期六
    • 太阳
  • 四季
    • 夏天
    • 冬天
    • 春天
    • 落下

离散数据非常适合放在枚举中,它可以帮助代码清晰和重用。连续数据是指没有间隙的数据,属于连续序列,如数字。这些可能会有所不同,具体取决于它们的测量:

  • 某人的体重
  • 汽车的速度

离散数据是一个很好的候选数据,它可以在枚举中使用,而连续数据不应该在枚举中使用。你能想象一个年龄的枚举吗?

enum Age {
  Zero,
  One,
  Two,
  Three,
  Four,
  Five,
  Six
}

这不是放置在枚举中的好候选,因为它需要不断更新和修改,从而导致维护噩梦。

您应该只考虑在枚举中添加离散的、高度稳定的数据类型。

结论

我希望这篇文章对您有所帮助,以便您更好地了解枚举是什么、它们解决的问题、合并两个枚举的用例以及如何实现它!快乐的黑客。

来源:https ://blog.logrocket.com/extend-enums-typescript/

#typescript 

What is GEEK

Buddha Community

如何在 TypeScript 中扩展枚举

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

Cayla  Erdman

Cayla Erdman

1601549700

What’s New In Typescript 4.0?

Today I am going to talk about new features in Typescript 4.0.

TypeScript 4.0 comes with lots of new features to make JavaScript development easier.

Labeled Tuple Elements

You can label tuple elements.

You can write:

type Range = [start: number, end: number];

to restrict args to have a string and a number.

you can also write:

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

to have rest entries in your tuple.

If your tuple has type Foo, then the tuple starts with a number and a string.

Then the rest of the entries can be anything.

Labels don’t require you to name your variables differently when destructuring.

For example, if you have:

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

then you can name the destructured variables anything you want.

#software-development #typescript-with-react #typescript #typescript-4 #react native

许 志强

许 志强

1656578280

如何在 TypeScript 中扩展枚举

TypeScript 受到开发者社区的喜爱有很多原因,其中之一是因为它为其中编写的代码提供了静态检查。

在开发生命周期的早期发现问题可以节省几天调试随机、模糊错误的时间,这些错误有时会在使用JavaScript 等动态语言时弹出。

TypeScript 可以帮助您的代码更可预测和更好地记录,使重构更容易,并帮助减少您在生产应用程序运行时可能遇到的潜在错误。它的受欢迎程度和力量体现在其 93% 的开发者满意度和在过去五年中飙升的使用率上。

对 TypeScript 至关重要的一种语言机制是枚举。 

TypeScript 中的枚举是什么?

有趣的是,枚举不是打字的特性,就像大多数 TypeScript 一样——事实上,它们是为数不多的增强语言的新特性之一。

枚举允许开发人员为变量定义一组严格的选项。例如:

enum Door {
  Open,
  Closed,
  Ajar // half open, half closed
}

枚举默认为数字枚举,所以上面的枚举本质上是一个以0, 1, 和2为键的对象,我们可以在转译的JavaScript 代码中看到。

"use strict";
var Door;
(function (Door) {
    Door[Door["Open"] = 0] = "Open";
    Door[Door["Closed"] = 1] = "Closed";
    Door[Door["Ajar"] = 2] = "Ajar"; // half open, half closed
})(Door || (Door = {}));
console.log(Door.FullyOpened);

在 TypeScript 中,您还可以使用字符串枚举,如下所示:

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}

如果您随后使用此Door枚举,则可以确保变量仅使用枚举中指定的三个选项。因此,您不能意外分配错误或以这种方式轻松创建错误。

如果您确实尝试使用另一个变量,它将引发如下类型错误:

 

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}
console.log(Door.FulyOpened)

Property 'FullyOpened' does not exist on type 'typeof Door'.

为什么我们需要扩展一个枚举?

扩展是面向对象的四大支柱之一,是 TypeScript 中存在的语言特性。扩展枚举允许您从本质上复制变量定义并添加一些额外的东西。

因此,例如,您可能正在尝试执行以下操作:

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}

enum DoorFrame extends Door { // This will not work!
  Missing = "noDoor"
}

console.log(DoorFrame.Missing)

然后,我们可以将额外的属性添加到枚举中,甚至将两个枚举合并在一起,以仍然对我们的枚举进行严格的键入,同时还可以在定义它们之后更改它们。

但请注意,上面的代码片段不起作用!它无法转换并引发四个不同的错误。

你能扩展枚举吗?

简短的回答是否定的,你不能扩展枚举,因为 TypeScript 没有提供扩展它们的语言功能。但是,您可以使用一些变通方法来实现继承。

TypeScript 中的类型交集

enum Door {
  Open = "open",
  Closed = "closed",
  Ajar = "ajar" // half open, half closed
}

enum DoorFrame {
  Missing = "noDoor"
}

type DoorState = Door | DoorFrame; 

在上面的代码块中,我们使用了一个交集类型。交集就像一个“或”,它只是意味着DoorState类型要么是 type 要么Door是 type DoorFrame

这现在意味着DoorState可以互换使用两个枚举中的任何一个变量。

传播语法

我们在之前的转译代码中已经看到,枚举变成了一个 JavaScript 对象,具有您的枚举指定的键和值。

在 TypeScript 中,如果我们愿意,我们可以编写纯 JavaScript。事实上,这是 TypeScript 的一大优势。例如,您可以将所有代码重命名file.jsfile.ts并关闭编译器对代码的检查。只要您运行编译/转换步骤,一切都会正常运行,代码更改为零。

我们可以通过知道当我们的枚举变成 JavaScript 时,它将是一个 JavaScript 对象字面量并使用扩展语法来利用它,如下所示

enum Move {
  LEFT = 'Left',
  RIGHT = 'Right',
  FORWARD = 'Forward',
  BACKWARD = 'Backward'
}
const myMove = {
  ...Move,
  JUMP: 'Jump'
}

但是,此解决方案已在第二次进行了描述,因为它不如交叉类型的解决方案好,因为它不如我们的第一个解决方案强大。这是因为枚举的“组合”发生在运行时,而当我们使用类型交集时,类型检查可以发生在编译/转译时,而不是运行时。

TypeScript 枚举最佳实践

我们已经讨论了如何在 Typescript 中扩展枚举,但枚举并不是解决所有问题的灵丹妙药。如果使用不当,枚举会使您的代码可读性、可伸缩性和可维护性更差,而不是改进您的代码。

因此,让我们介绍一些在 TypeScript 中使用枚举时使用的最佳实践和常见模式。

1. 避免异构枚举

我已经解释了我们如何拥有这样的字符串枚举:

enum Seasons {
  Summer = "Summer",
  Winter = "Winter",
  Spring = "Spring",
  Fall = "Fall"
}

除了有这样的数字枚举:

enum Decision {
  Yes,
  No
}

但是,还有第三种类型的枚举,您可能不知道,称为异构枚举。这是您可以在同一个枚举中使用字符串和数字枚举的地方。

文档中的一个示例是这样的:

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

重要的是要注意,即使是文档也不鼓励这种做法,因为在这种情况下,使用这种方法表明您可能需要:

  • 重新考虑这两个变量之间的关系
  • 创建两个单独的枚举
  • 使它们都符合一种数据类型

2. “枚举即配置”反模式

有时代码功能可能被迫遵守枚举选项,这很快就会变成反模式。

这是一个例子

enum Operators {
  Add,
  Subtract
}
function calculate(op: Operators, firstNumber: number, secondNumber: number) {
  switch(op) {
    case Operators.Add: return firstNumber + secondNumber
    case Operators.Subtract: return firstNumber - secondNumber
  }
} 

上面的代码看起来相当简单和安全,因为我们的例子确实是简单和安全的。

但是在大型代码库中,当您将实现细节严格绑定到这样的枚举类型时,可能会导致一些问题:

  • 您创建了两个事实来源(如果枚举更改,则枚举和函数都需要更新)
  • 这种模式将在代码周围传播元数据
  • 代码块不再是通用的

如果您需要执行上述操作,则更简单(更简洁)的模式可能如下所示。

const Operators = {

  Add: {
    id: 0,
    apply(firstNumber: number, secondNumber: number) { return firstNumber + secondNumber }
  },

  Subtract: {
    id: 1,
    apply(firstNumber: number, secondNumber: number) { return firstNumber - secondNumber }
  }
}

您可以在此处此处阅读有关此模式的更多信息。

3.枚举最能代表的数据类型

通常有一种方法可以将代码中使用的不同类型的数据组合在一起:离散变量或连续变量。

离散变量是在它们的表示之间有空格的数据,并且只有几个表示。这里有一些例子:

  • 一周中的日子
    • 星期一
    • 周二
    • 星期三
    • 星期四
    • 周五
    • 星期六
    • 太阳
  • 四季
    • 夏天
    • 冬天
    • 春天
    • 落下

离散数据非常适合放在枚举中,它可以帮助代码清晰和重用。连续数据是指没有间隙的数据,属于连续序列,如数字。这些可能会有所不同,具体取决于它们的测量:

  • 某人的体重
  • 汽车的速度

离散数据是一个很好的候选数据,它可以在枚举中使用,而连续数据不应该在枚举中使用。你能想象一个年龄的枚举吗?

enum Age {
  Zero,
  One,
  Two,
  Three,
  Four,
  Five,
  Six
}

这不是放置在枚举中的好候选,因为它需要不断更新和修改,从而导致维护噩梦。

您应该只考虑在枚举中添加离散的、高度稳定的数据类型。

结论

我希望这篇文章对您有所帮助,以便您更好地了解枚举是什么、它们解决的问题、合并两个枚举的用例以及如何实现它!快乐的黑客。

来源:https ://blog.logrocket.com/extend-enums-typescript/

#typescript 

Christa  Stehr

Christa Stehr

1599308024

Microsoft Releases TypeScript 4.0 With Speed Boosting Features

icrosoft recently announced the availability of TypeScript version 4.0. The developers at the tech giant claimed that this version of the language represents the next generation of TypeScript with more expressivity, productivity as well as scalability.

Developed by the tech giant, TypeScript is an open-source programming language that is built on top of JavaScript by adding syntax for static type definitions. The types in this language provide a way to describe the shape of an object, providing better documentation as well as allowing TypeScript to validate that the code is working correctly.

According to the latest Stack Overflow Developers survey 2020, it secured the second position as the most loved language and  9th position among 25 programming languages as the most commonly used programming language by the developers. In one of our articles, we discussed how TypeScript weighs over other programming languages.

It is one of the fastest-growing programming languages among the developers. The motive behind this language is that while writing down the types of values and where they are used, developers can use TypeScript to type-check the code and let them know about mistakes before they run the code. TypeScript compiler can be used to strip away types from the code, leaving them with clean, readable JavaScript that runs anywhere.

In the present scenario, TypeScript is a core part of many developer’s JavaScript stack. The language adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host and on any operating systems.

The program manager of TypeScript, Daniel Rosenwasser, said in a blog post, “In our past two major versions, we looked back at some highlights that shined over the years. For TypeScript 4.0, we’re going to keep up that tradition.”

What’s New?

Based on the feedback by the developer’s community, TypeScript 4.0 includes many intuitive features that are focussed on boosting the performance of this language. Some of them are mentioned below-

Speed Improvements in build mode with –noEmitOnError

According to Rosenwasser, previously, compiling a program after a previous compile with errors under incremental would result in extremely slow performance when using the –noEmitOnError flag. The reason is, none of the information from the last compilation would be cached in a .tsbuildinfo file based on the –noEmitOnError flag.

But now TypeScript 4.0 changes this. The new update provides a great speed boost in these scenarios, and in turn, improves the build mode scenarios, which imply both –incremental and –noEmitOnError.

#developers corner #microsoft #microsoft releases typescript 4.0 #programming language #programming language with high salary #typescript #typescript 4.0

Yoshiko  Jones

Yoshiko Jones

1603953021

What is TypeScript? Why TypeScript? and Why Not TypeScript?

Maybe you’ve been using JavaScript for a while and you’ve been hearing the buzz around… TypeScript. In this 2 part series, we’ll take a look at Why TypeScript? and Why Not TypeScript?

What is TypeScript?

According to the TypeScript website “TypeScript extends JavaScript by adding Types… TypeScript code is transformed into JavaScript code via the TypeScript compiler or Babel. This JavaScript is clean, simple code which runs anywhere JavaScript runs…”. In short, many refer to TypeScript as a superset of JavaScript.

In my opinion, this is kind of true and kind of not. Technically, not all valid JavaScript code can also be TypeScript code. We’ll talk about that later on. But, at its core, TypeScript was designed to allow developers to turn JavaScript, a dynamic programming language (one that is interpreted at runtime) into a statically typed programming language (one that is compiled before running). Let’s dive in.

Reasons For TypeScript

Improved Code Quality (potentially)

TypeScript makes use of features similar to languages like C## or Java: it truly is object oriented. This allows for more robust code. It enables the developer to implement type checking and make use of interfaces, classes, inheritance, etc. This can up the game as far as clean code when looking at a JavaScript program and a TypeScript program.

_Why did you throw in the word _potentially? Well, most valid JavaScript code can become TypeScript code. This means you don’t have to use the object oriented or typed features of TypeScript. Remember, TypeScript is optionally typed. It is not required. If TypeScript is utilized merely like JavaScript then improved code quality may not actually be a thing.

#typescript #programming #javascript #web-development #developer