Abstract: Learn the TS way of thinking.

  • TypeScript – A way of thinking
  • Author: zhangwang

FundebugReprinted with authorization, the copyright belongs to the original author.

There’s an idea in The movie Arrival that language affects the way people think, and for front-end engineers, developing in typescript is an attempt to think differently.

It wasn’t until recently that I started learning typescript systematically, and it took me about a month or so. Before this, I also used TS in some projects to copy other people’s writing methods, but to be fair, BEFORE this round of systematic learning, I did not understand TS. More than a month ago, I understood THAT TS was a tool that could constrain types, but now I realize that TS is not simply a tool, and using it will affect the way I think when writing code.

How does TS affect the way I think

For front-end developers, TS reinforces the idea of programming to interfaces. We know that a slightly complex program is inseparable from the coordination of different modules, and the functions of different modules should be clearer. TS can help us to sort out different interfaces.

Explicit module abstraction process

One of the effects of TS on the way I think is that I now consider thinking about abstractions and extensions as a necessary part of writing a module. Of course a good developers writing programs in any language, consider abstract and development is a necessary link, but if you list used in our daily life, you will understand TS through the interface of the contents of this abstract clear for concrete meaning, any content is not clear, it is a bit like the content of the optional, often easy to be ignored.

For example, for example, we use the TS define a function that TS will require us to function parameters and return values have a clear definition, simple definition of some type, but it can help us locate function role, for example we set its return value type is void, it clearly shows that we want to take advantage of the side effects of this function.

Having the abstraction clear makes sense for future code changes, and we don’t have to worry about forgetting what was conceived before, which is perhaps even more important when working with multiple people.

Of course, you can use tools like Jsdoc to make the abstraction of a function explicit, but it’s not as mandatory, so it’s not necessarily as effective, but jsdoc can be used as a supplement to TS.

Write code with more confidence

TS also makes me more confident in writing front-end code. This confidence comes from TS, which can help us avoid many bugs that may be caused by our own neglect. In fact, there is a special study on TS assistance To avoid bugs, one called To Type or Not To Type: Quantifying Bugs in JavaScript: Using TS for static type checking can reduce Bugs by at least 15%.

Let me give you an example of how TS gave me this confidence.

The following statement, which you’re familiar with, is that the DOM provides a way to get an element based on its ID.

const a = document.getElementById("a")
Copy the code

For myself, before using TS, I ignored the possibility that document.getElementById’s return value might be null, an inadvertant omission that may cause an unexpected bug in the future.

With TS, the editor explicitly reminds us that a may be null.

We don’t have to deal with null values, but use const a = document.getelementByID (‘id’)! We can explicitly tell TS that it won’t be null, but at least we know exactly what we want to do.

The process of using TS is a learning process

After using TS, I felt like I spent much less time looking up documents through the browser. Whether it’s a library, native JS or nodeJS, or even a type defined by another member of your team. Combined with VSCode, there are very smart alerts and it is easy to see the exact definition of the corresponding interface. The process of use is a process of deepening understanding, and indeed “programming to interfaces” is naturally more intimate with static typing.

For example, if we use the Color library, VSCode will have a reminder like this:

You don’t have to look at the documentation to see the API it provides. If we look at the source file for the library, we can see that the reason for the reminder is the following definition:

// @types/color/index.d.TSinterface Color { toString(): string; toJSON(): Color; string(places? : number): string; percenTString(places? : number): string; array(): number[]; object(): { alpha? : number } & { [key: string]: number }; unitArray(): number[]; unitObject(): {r: number, g: number, b: number, alpha? : number }; . }Copy the code

This kind of reminder can certainly improve the efficiency of development, and although defining types may take some time early on, it is well worth using TS for a large project with long-term maintenance.

A way to learn typescript

Maybe it was because I had never studied a static language systematically before, so it took me a lot of effort to get the feeling that I had basically learned TS from the beginning. In the process of learning TS, I mainly refer to the following materials. You can directly click the link to view, or you can continue to read the article. I have some simple analysis of these materials.

  • TypeScript faced – the book
  • TypeScript Deep Dive — book
  • TypeScript – React – Starter – making
  • The react – typescript – cheaTSheet – making
  • Advanced Static Types in TypeScript – egghead. IO
  • Use TypeScript to develop React Applications — egghead. IO
  • Practical Advanced TypeScript – egghead. IO
  • Ultimate React Component Patterns with Typescript 2.8 — medium
  • The TypeScript Tax — medium

In the process of reading the above information, I rewrote a simple but complete CRA-based front-end project using TS, and now feel that I can handle the common requirements of development work using TS. If you are new to TS, follow the following path.

Set up the TS operating environment

Don’t get me wrong, it’s not built from scratch. When we study practical content, we can learn it faster by practicing. If you use React, it’s easy to build a TS based project using YARN or create-React-app.

Execute the following command on the command line to produce an item that can be used directly:

# to use yarn
$ yarn create react-app TS-react-playground --typescript
# use NPX
$ npx create-react-app TS-react-playground --typescript
Copy the code

You can then add additional configuration in tsconfig.json if desired.

Personally, I like to synchronize T-Lint with prettier, so I don’t have to worry about formatting later on. For details on how to Configure TypeScript, TSLint, and Prettier in VS Code for React Native Development, see my configuration log.

If you don’t use React, the TypeScript homepage provides a way to use TS with other frameworks.

Understand key concepts

I have always felt that it is important to know the boundaries of a new skill, and the relevant details can be gradually understood in the subsequent use process. As we all know, TS is a superset of JS, so the first thing to learn about TS is to find out where the “super” boundary is.

At this stage, it’s recommended to read the TypeScript Handbook — Book, which is actually the official handbook for getting started. The link here is the Chinese translation version of the link, the translation quality is very good, although the content is not new English official documents, but it is best to learn new things from their most familiar with the content, so might as well first see the Chinese document. All the examples encountered in the reading process can be practiced in the ts-playground built above to get familiar with them.

TS as a superset of JS, its “super” is actually mainly in two aspects

  • TS introduces a type system for JS;
  • TS supports some syntax that is not part of the formal ECMAScript standard, such as decorators.

On the second point, TS does something similar to Babel, so some people say that TS is the biggest threat to Babel. Most likely, you’ve already used these new grammars, so I won’t go over them here.

What’s harder to understand is the type system, which has its own Declaration Spaces, some of its own keywords and syntax.

For me, the biggest difficulty in learning TS lies in the fact that there are some concepts in this type system that I have little knowledge about before. I can summarize them here.

Some new concepts in TS

Programming is actually the process of operation and processing of data. The type system can help us operate on the data more accurately. The core of TypeScript is that it provides a type system that allows us to constrain data types. Sometimes constraints are simple, sometimes they are abstract.

TS support type is as follows: Boolean, number, string, [], the Tuple, enum, any, void, null, and undefined, never, Object.

The more complex data structures in TS are actually combinations of the above types. For the basics of types, I recommend reading the Basic Types section first. Here are the concepts that initially bothered me:

  • Enum: Now think about itenumEnumerations are very useful, and many other languages have them built in. Using them properly can make our code more readable. For example:
const enum MediaTypes {
  JSON = "application/json"
}

fetch("https://swapi.co/api/people/1/", {
  headers: {
      Accept: MediaTypes.JSON
  }
})
.then((res) = > res.json())
Copy the code
  • Never:neverMeans that the code will never be executed here, and can often be applied toswitch casedefaultIn case we missed anythingcaseUntreated, such as:
enum ShirTSize {
  XS,
  S,
  M,
  L,
  XL
}

function assertNever(value: never) :never {
  console.log(Error(`Unexpected value '${value}'`));
}

function prettyPrint(size: ShirTSize) {
  switch (size) {
      case ShirTSize.S: console.log("small");
      case ShirTSize.M: return "medium";
      case ShirTSize.L: return "large";
      case ShirTSize.XL: return "extra large";
        // case ShirTSize.XS: return "extra small";
      default: returnassertNever(size); }}Copy the code

Below is a screenshot of the above code in my editor, which tells us that there are still unhandled conditions with an error.

  • Type assertion: Type assertion is when you tell the compiler that a value has a certain type. There are two different ways to add type assertions:
  • <string>someValue
  • someValue as string

The problem with type assertions when I look at the documentation is that I can’t think of any circumstances in which to use them. It turns out that when you know there’s a feature, you’ll find it useful when you actually use it, such as migrating legacy projects.

  • Generics: Generics make our data structures more abstract and reusable, and because of this abstraction, it’s sometimes not easy to understand. Generics can be used in a wide range of scenarios, such as:
type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};
Copy the code

The ability to make all subtypes of an interface null. I remember finding generics confusing the first time I saw them, but after using them a few times, I found them ok.

  • Interface and typeinterfacetypeCan be used to define some complex type structures, and in most cases are generic. At first I never understood what the difference was between the two, but it turned out that the difference was:
    • interfaceYou create a new type, and type is just an alias, it’s a reference;
    • If the type USES the union operator (|) operator, then the type are not implements to the class;
    • If type is usedunion(|) operator, it can not be usedextends interface
    • A type cannot be merged like an interface. It is unique in scope. [1]

In the video Use Types vs. Interfaces from @volkeron on @eggheadio, this distinction is illustrated in more detail with examples.

It’s worth pointing out that the TypeScript Handbook distinction between type and interface is still in TS 2.0. The corresponding chapter is currently inaccurately described. See Interface vs Type Alias in TypeScript 2.7 for more information.

  • Type protection the TS compiler will analyze our program and specify the exact type possible for a variable in the specified scope. Type protection is an auxiliary method of type determination. The following statements can be used as type protection:
    • typeof padding === "number"
    • padder instanceof SpaceRepeatingPadder

An application instance can be combined with the Reducer type in Redux. According to different types, TS can identify the action type in different scopes.

  • Type mapping Type mapping is a way TypeScript provides to create new types from old types. They are very practical. For example, if we wanted to quickly make all properties in an interface optional, we could write this:
interface Person {
    name: string;
    age: number;
}
type PartialPerson = { [P inkeyof Person]? : Person[P] }Copy the code

There is also the concept of mapping types, which TS has built-in mapping types (actually syntactic sugar) that allow us to easily map types. For example, with the built-in mapping type Partial, the above expression can be written as follows:

interface Person {
    name: string;
    age: number;
}
type PartialPerson = Partial<Person>
Copy the code

For more common mapping types, see this article — the use and implementation of some GENERics in TS tools. In addition to padding (such as Readonly), this article also mentions some useful mapping types (such as padding) that aren’t built into TS (such as padding).

  • It is difficult to guarantee that third-party libraries all support TS types natively. After you have used TS for a while, you must have installed something like this@types/xxxWhen you install a library like this, you actually install a description file for the library. The type definitions for these third-party libraries are stored inDefinitelyTypedIn this repository, the commonly used third-party libraries are defined here. inTypeSearchYou can search for third-party library type definition packages in the

There are a lot of other things about types, but some are less common and some are less difficult to understand, so I won’t go into them here.

The new concept of elimination

When I first started reading TypeScript Handbook, I did think I knew a lot, but I found that when I started writing code, I kept getting stuck. The reason for this may be that we have received too many new concepts at once, some of which we have not had time to digest. At this time, I recommend the following online course:

  • Advanced Static Types in TypeScript – egghead. IO

Watching videos is a relatively easy way to study. The course is about an hour long. We’ll go through some of the more important concepts in the TypeScript Handbook with examples. You can follow the tutorial to type out the example once, and read the hints given in vscode more often. By the end of the tutorial, you will surely have a deeper understanding of some of the core concepts of TS.

Imitate and practice

To really master TS, practice is essential. It is also a good practice to imitate TypeScript. For example, React + TypeScript.

  1. Typescript-react-starter, this is a great source for TS beginners. You can continue to use the playground we built above by writing once in the repository’s readMe. So you’ll get the basics of TS and React;
  2. GitHub – React-typescript -cheaTSheet, this tutorial is also relatively simple, but the one above takes it a step further, and after continuing to remodel our playground based on its readMe, we learn that React + Redux + TypeScript
  3. React-redux-typescript – Guide shows you how to apply some of the more complex typescript patterns. You can also use the react-Redux-typescript for your own projects.
  4. Ultimate React Component Patterns with Typescript 2.8 Ultimate React Component Patterns with Typescript 2.8 You can almost see how to use TS to deal with the various React component patterns.
  5. Use TypeScript to develop React Applications — egghead. IO. Use TypeScript to develop React Applications — Egghead.

At this point, you should have basic TS development capabilities and be able to develop relatively complex applications in combination with TS independently.

Deeper understanding

Of course, you may not be satisfied with knowing how to use TS, but you want to know how TS works. Here are two recommended readings:

  • TypeScript Compiler Internals · TypeScript Deep Dive, TS Compiler core is AST, This article shows how the five phases of TS compilation (Scanner /Parser/Binder /Checker /Emitter) work.
  • Learn how to contribute to the TypeScript compiler on GitHub through a real-world example. Learn how to contribute to the TypeScript compiler on GitHub through a real-world example

I haven’t had time to look at the principle of TS. However, THERE are many applications of AST in front end. After I add more relevant knowledge, I may have a more comprehensive summary of AST.

The TypeScript Tax [2] is a very good article. Reading The TypeScript Tax [2] can help us to have a more objective view of TS. From The author’s point of view, TS has more disadvantages than advantages. The main reason is that most of the functions provided by TS can be replaced by other tools to some extent, and the type system requires too much extra code to write. The type system also undermines the flexibility of dynamic languages to some extent, making it difficult to apply some dynamic langue-specific patterns. Author final conclusion with strong subjective color, I am not is well accepted, but the analysis process of this article is very wonderful, TS features and compares the JS ecological now, can make us have a more comprehensive knowledge of TS, highly recommend reading, maybe you will like me, after seeing the analysis process, Would be more interested in TS.

A new minor version of TS is released every few months, and each minor version is noted on the TypeScript blog [3] as a reference to follow up on TS.

Recommended reading

The following references are in the article, and there are links to them. If you’ve seen them all, you don’t need to check them again.

  • TypeScript faced – the book
  • TypeScript Deep Dive — book
  • TypeScript – React – Starter – making
  • The react – typescript – cheaTSheet – making
  • Advanced Static Types in TypeScript – egghead. IO
  • Use TypeScript to develop React Applications — egghead. IO
  • Practical Advanced TypeScript – egghead. IO
  • Ultimate React Component Patterns with Typescript 2.8 — medium

reference

  • Handbook’s description of the difference between interface and type is outdated. See Interface vs Type Alias in TypeScript 2.7
  • The TypeScript Tax describes The pros and cons of TS in great detail, and it is highly recommended to read The TypeScript Tax
  • Ts update, can see the official blog address here [devblogs.microsoft.com/typescript/