我是靠谱客的博主 冷静可乐,最近开发中收集的这篇文章主要介绍TypeScript指南,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Few technologies in the last few years had the impact that TypeScript had.

在过去的几年中,很少有技术能够像TypeScript一样产生影响。

Let me add a little bit of social proof in favor of TypeScript.

让我添加一些社会证据来支持TypeScript。

The “The State of JavaScript 2018” survey, almost 50% of respondents said they used TypeScript, and would use it again. over 30% said they would like to learn it. That’s a huge percentage of people interested in it.

在“ JavaScript状况2018”调查中,几乎50%的受访者表示他们使用了TypeScript,并将再次使用它。 超过30%的人说他们想学习。 对它感兴趣的人占很大比例。

TypeScript is built by Microsoft, which is not new to creating programming languages, and one of its creators is Anders Hejlsberg, a danish software engineer who is known for Turbo Pascal (❤️) and Delphi. I put the heart next to Turbo Pascal because Pascal was my first programming language and we used Turbo Pascal at school.

TypeScript是由Microsoft构建的,它对创建编程语言并不陌生,其创建者之一是丹麦软件工程师Anders Hejlsberg,他以Turbo Pascal(❤️)和Delphi闻名。 我之所以选择Turbo Pascal,是因为Pascal是我的第一门编程语言,而我们在学校使用过Turbo Pascal。

It’s an open source language, developed in public at https://github.com/Microsoft/TypeScript.

这是一种开源语言,在https://github.com/Microsoft/TypeScript上公开开发。

Angular is all about TypeScript, Vue.js is said to make version 3 using TypeScript. Ryan Dahl, the creator of Node.js, said great things about it too.

Angular与TypeScript有关,据说Vue.js使用TypeScript制作版本3。 Node.js的创建者Ryan Dahl也对此表示了赞赏。

I think those things help you put TypeScript in perspective. It’s not just a random JavaScript flavor that will die next month, it’s definitely here to stay. And as things go, this means you are likely required to use it in a future project, or at your next job. Maybe it will help you get a job too, so let’s just dive into it.

我认为这些东西可以帮助您正确看待TypeScript。 不仅仅是随机JavaScript风格会在下个月消失,它肯定还会保留。 随着事情的发展,这意味着您可能需要在将来的项目中或在下一份工作中使用它。 也许它也会帮助您获得一份工作,所以让我们开始吧。

编写并编译您的第一个TypeScript文件 (Write and compile your first TypeScript file)

Starting with TypeScript is easy. If you ever wrote a line of JavaScript, you already wrote TypeScript code!

从TypeScript开始很容易。 如果您曾经编写过一行JavaScript,那么您已经编写了TypeScript代码!

This odd statement I made is one of the reasons for TypeScript’s success: it’s a strict superset of JavaScript.

我做出的这个奇怪的陈述是TypeScript成功的原因之一:它是JavaScript的严格超集

It’s a bit like what SCSS is for CSS.

有点像SCSS是CSS。

In particular, it’s a superset of ECMAScript 2015 (also known as ES6). This means that any valid JavaScript is also valid TypeScript.

特别是ECMAScript 2015 (也称为ES6)的超集。 这意味着任何有效JavaScript也是有效的TypeScript。

Many of the features of TypeScript are equivalent to the JavaScript ones. For example variables, the module system, iterators and more.

TypeScript的许多功能与JavaScript等效。 例如变量,模块系统,迭代器等等。

So, there’s no need to write your absolute first TypeScript file, because you already did without knowing so, but let’s make a little “hello world!” by explicitly making a TypeScript file, and compile that to JavaScript.

因此,无需编写绝对的第一个 TypeScript文件,因为您已经不知道这样做了,但是让我们做个“ hello world”吧。 通过显式创建TypeScript文件,并将其编译为JavaScript。

Run npm install -g typescript to globally install the TypeScript compiler, available to you using the tsc command.

运行npm install -g typescript以全局安装TypeScript编译器,您可以使用tsc命令使用它。

Make a new folder, and create an app.ts file. ts is the TypeScript file extension.

新建一个文件夹,然后创建一个app.ts文件。 ts是TypeScript文件扩展名。

Write this first program:

编写第一个程序:

const greet = () => {
console.log('Hello world!')
}
greet()

This is just plain JavaScript, but stored in a .ts file.

这只是普通JavaScript,但存储在.ts文件中。

Now compile the program using tsc app.ts. The result will be a new JavaScript file: app.js, with this content:

现在使用tsc app.ts编译程序。 结果将是一个新JavaScript文件: app.js ,其内容如下:

var greet = function () {
console.log('Hello world!');
};
greet();

The TypeScript code has been compiled to JavaScript. The JavaScript code changed a little bit, for example you can notice it added semicolons, and used var instead of const, and used a regular function instead of the arrow function.

TypeScript代码已编译为JavaScript。 JavaScript代码稍有变化,例如,您可以注意到它添加了分号,并使用var而不是const ,并使用常规函数而不是arrow函数。

It looks like old JavaScript, right? This is because TypeScript compiles to ES5 by default, as this is the ECMAScript version that is almost guaranteed to be supported in all modern browsers. You can change the compilation target to other versions,for example to target ES2018 use tsc app.ts --target ES2018:

看起来像旧的 JavaScript,对不对? 这是因为TypeScript默认情况下会编译为ES5,因为几乎可以肯定所有现代浏览器都支持ECMAScript版本。 您可以将编译目标更改为其他版本,例如使用tsc app.ts --target ES2018定位为目标:

const greet = () => {
console.log('Hello world!');
};
greet();

See, here almost nothing changed from our original .ts file except for the additional semicolons.

请参阅此处,除了其他分号外,几乎与原始.ts文件没有任何更改。

There is a very convenient online playground that lets you play around with the TypeScript to JavaScript compilation, at https://www.typescriptlang.org/play/.

在https://www.typescriptlang.org/play/上有一个非常方便的在线游乐场,可让您使用TypeScript到JavaScript进行编译。

打字 (Typing)

Typing is the key TypeScript feature.

键入是TypeScript的关键功能。

So far we compiled a .ts file, but we just compiled plain JavaScript.

到目前为止,我们已经编译了.ts文件,但是我们只是编译了普通JavaScript。

You saw one first feature of TypeScript: you can use modern JavaScript and compile it to ES5 (or higher), kind of what Babel does.

您看到了TypeScript的第一个功能:您可以使用现代JavaScript并将其编译为ES5(或更高版本),这与Babel一样。

We didn’t use any of the TypeScript functionalities.

我们没有使用任何TypeScript功能。

The most important piece of functionality provided by TypeScript is the type system: static types, interfaces, type inference, enums, hybrid types, generics, union/intersection types, access modifiers, null checking.

TypeScript提供的最重要的功能是类型系统:静态类型,接口,类型推断,枚举,混合类型,泛型,联合/交叉类型,访问修饰符,空检查。

If you ever used a typed language, like Go or C, you already know how this works. If not, and you only programmed in a dynamic language like Python or Ruby, this is all new to you but don’t worry.

如果您曾经使用过像Go或C这样的打字语言,那么您已经知道它是如何工作的。 如果不是这样,而您只使用Python或Ruby之类的动态语言进行编程,这对您来说是新手,但请不要担心。

The type system allows you, for example, to add types to your variables, function arguments and function return types, giving a more rigid structure to your programs.

例如,类型系统允许您将类型添加到变量,函数参数和函数返回类型中,从而为程序提供更严格的结构。

The advantages are better tooling: the compiler (and editors like editors like VS Code) can help you a lot during development, pointing out bugs as you write the code. Bugs that couldn’t possibly be detected if you didn’t have types. Also, teamwork gets easier because the code is more explicit.

优势是更好的工具:编译器(以及诸如VS Code之类的编辑器之类的编辑器)在开发期间可以为您提供很多帮助,并指出编写代码时的错误。 如果没有类型,则可能无法检测到错误。 而且,由于代码更加明确,团队合作变得更加容易。

The resulting JavaScript code that we compile to does not have types, of course: they are lost during the compilation phase, but the compiler will point out any error it finds.

当然,我们编译得到JavaScript代码没有类型:它们在编译阶段会丢失,但是编译器会指出发现的任何错误。

Here is how you define a string variable in TypeScript:

这是在TypeScript中定义字符串变量的方式:

const greeting : string = "hello!"

Type inference lets us avoid writing the type in obvious cases like this:

类型推断使我们避免在类似这样的明显情况下编写类型:

const greeting = "hello!"

The type is determined by TS.

类型由TS确定。

This is how a function accepts an argument of a specific type:

这是函数接受特定类型的参数的方式:

const multiply = (a: number, b: number) => {
return a * b
}

If you pass a string to multiply(), the compiler will give you an error.

如果将字符串传递给multiply() ,则编译器将给您一个错误。

Here is how functions declare their return value:

以下是函数声明其返回值的方式:

const multiply = (a: number, b: number): number => {
return a * b
}

Valid types are

有效类型为

  • number

    number

  • string

    string

  • boolean

    boolean

  • enum

    enum

  • void

    void

  • null

    null

  • undefined

    undefined

  • any

    any

  • never

    never

  • Array

    Array

  • tuple

    tuple

any is a catch-all type that identifies, as its name says, any type.

any是一种万能类型,顾名思义,它可以标识任何类型。

班级 (Classes)

ES2015/ES6 added classes to JavaScript, as a simple syntactic sugar over the prototypal inheritance.

ES2015 / ES6在JavaScript中添加了类 ,作为对原型继承的简单语法糖。

Like it or not, under the hoods JavaScript is still using prototypal inheritance, with all its unique features and quirks.

不管喜欢与否,JavaScript仍在使用原型继承,并且具有所有独特的功能和怪癖。

TypeScript classes are a little bit different than JavaScript classes. The reason is that TypeScript introduced classes before JavaScript had them (they were introduced in ES2015/ES6).

TypeScript类与JavaScript类略有不同。 原因是TypeScript在JavaScript之前引入了类(它们是在ES2015 / ES6中引入的)。

Like in JavaScript, you declare classes in this way:

就像在JavaScript中一样,您可以通过以下方式声明类:

class Car {
}

This is how you define class fields:

这是定义类字段的方式:

class Car {
color: string
}

All fields are public by default. You can set a field to be private or protected:

默认情况下,所有字段都是公共的。 您可以将字段设置为私有受保护

class Car {
public color: string
private name: string
protected brand: string
}

Like it happens in other programming languages, private fields can only be accessed in the class that declares them. Protected fields can only be accessed by deriving classes as well.

就像在其他编程语言中一样,私有字段只能在声明它们的类中访问。 受保护的字段也只能通过派生类来访问。

You can also declare static fields, which are class fields rather than object fields:

您还可以声明静态字段,它们是类字段而不是对象字段:

class Car {
static numberOfWheels = 4
}

You can initialize fields with a constructor:

您可以使用构造函数初始化字段:

class Car {
color: string
constructor(theColor: string) {
this.color = theColor
}
}

This shorthand syntax makes it simpler:

这种简化的语法使其更简单:

class Car {
constructor(public color: string) {}
printColor() {
alert(this.color)
}
}
(new Car('red')).printColor()

Notice how we referenced the class field using this.x.

注意我们如何使用this.x引用类字段。

A field can also be read only:

一个字段也可以是只读的

class Car {
readonly color: string
}

and in this case its value can only be set in the constructor.

在这种情况下,其值只能在构造函数中设置。

Classes have methods:

类具有方法:

class Car {
color: string
constructor(public color: string) {
this.color = color
}
drive() {
console.log('You are driving the car')
}
}

Like in plain JavaScript, you create objects from those classes, using the new keyword:

就像在普通JavaScript中一样,您可以使用new关键字从这些类中创建对象:

const myCar = new Car('red')

and you can extend an existing class using the extend keyword:

您可以使用extend关键字扩展现有的类:

class ElectricCar extends Car {
//...
}

You can call super() in the constructor and in methods to call the extended class corresponding method.

您可以在构造函数和方法中调用super()来调用扩展类的对应方法。

存取器 (Accessors)

Fields can have getters and setters. Example:

字段可以具有getter和setter。 例:

class Car {
private _color: string
get color(): string {
return this._color
}
set color(color: string) {
this._color = color
}
}

抽象类 (Abstract classes)

Classes can be defined as abstract, which means there needs to be a class that extends it, and implements its eventual abstract methods:

可以将类定义为抽象类,这意味着需要一个扩展它的类,并实现其最终的抽象方法:

abstract class Car {
abstract drive()
}
class SportsCar extends Car {
drive() {
console.log('You are driving a sports car')
}
}

介面 (Interfaces)

Interfaces build upon basic types. You can use an interface as a type, and this interface can contain other type definitions:

接口建立在基本类型上。 您可以将接口用作类型,并且此接口可以包含其他类型定义:

interface SetOfNumbers {
a: number;
b: number;
}
const multiply = (set: SetOfNumbers) => {
return set.a * set.b
}
multiply({ a:1, b: 2 })

An interface can also be an interface for a class implementation:

接口也可以是类实现的接口:

interface Car {
name: 'string'
new (brand: string)
drive(): void
}
class SportsCar implements Car {
public name
construtor(public brand: string) {
//...
}
drive() {
console.log('You are driving a sports car')
}
}

功能特点 (Functions features)

Functions can have optional parameters using the ? symbol after the parameter name:

函数可以使用?来包含可选参数? 参数名称后的符号:

class Car {
drive(kilometers?: number) {
if (kilometers) {
console.log(`Drive the car for ${kilometers} kilometers`)
} else {
console.log(`Drive the car`)
}
}
}

and parameters can also have default values:

和参数也可以具有默认值:

class Car {
drive(kilometers = 10) {
console.log(`Drive the car for ${kilometers} kilometers`)
}
}

A function can accept a varying number of parameters by using rest parameters:

一个函数可以通过使用rest参数来接受不同数量的参数:

class Car {
drive(kilometers = 10, ...occupants: string[]) {
console.log(`Drive the car for ${kilometers} kilometers, with those people on it:`)
occupants.map((person) => console.log(person))
}
}
(new Car()).drive(20, 'Flavio', 'Roger', 'Syd')

枚举 (Enums)

Enums are one great way to define named constants, which is unfortunately not supported by JavaScript, but popularized by other languages.

枚举是定义命名常量的一种好方法,不幸的是,JavaScript不支持枚举常量,但其他语言也普遍使用枚举。

TypeScript gives us enums:

TypeScript为我们提供了枚举:

enum Order {
First,
Second,
Third,
Fourth
}

TS internally assigns an unique identifier to each of those values, and we can reference Order.First, Order.Second and so on.

TS在内部为每个值分配一个唯一的标识符,我们可以引用Order.FirstOrder.Second等。

You can assign values to the constants explicitly:

您可以将值显式分配给常量:

enum Order {
First = 0,
Second = 1,
Third = 2,
Fourth = 3
}

or also use strings:

或也使用字符串:

enum Order {
First = 'FIRST',
Second = 'SECOND',
Third = 'THIRD',
Fourth = 'FOURTH'
}

泛型 (Generics)

Generics is a feature that’s part of many different programming languages. In short, you can create a function, interface or class that works with different types, without specifying the type up front.

泛型是许多不同编程语言的一部分的功能。 简而言之,您可以创建适用于不同类型的函数,接口或类,而无需预先指定类型。

But at compile time, if you start using that function with a type and then you change type (e.g. from number to string), the compiler will throw an error.

但是在编译时,如果您开始使用带有类型的函数,然后更改类型(例如,从数字更改为字符串),则编译器将引发错误。

We could do this by omitting types at all or using any, but with generics all the tooling is going to be able to help us.

我们可以通过完全不使用类型或使用any来做到这一点,但是使用泛型,所有工具都将能够为我们提供帮助。

Example syntax:

语法示例:

function greet<T>(a : T) {
console.log(`Hi ${a}!`)
}
greet('Flavio')

The funny T symbol identifies a generic type.

有趣的T符号标识通用类型。

The type can be restricted to a certain class family or interface, using the extends keyword:

可以使用extends关键字将类型限制为特定的类系列或接口:

interface Greetable { name: string }
function greet<T extends Greetable>(a : T) {
alert(`Hi ${a.name}!`)
}
greet({ name: 'Flavio'})

我已经准备好了! (I am ready for more!)

Those are the basics of TypeScript. Go ahead to the official docs to learn all the details, or start writing your apps and learn as you do!

这些是TypeScript的基础。 继续阅读官方文档以了解所有详细信息,或开始编写应用程序并按需学习!

翻译自: https://flaviocopes.com/typescript/

最后

以上就是冷静可乐为你收集整理的TypeScript指南的全部内容,希望文章能够帮你解决TypeScript指南所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部