【Handbook 摘要】:Basics(01)

2021-06-15 10:13:58 浏览数 (1)

代码语言:javascript复制
目录
1. About this Handbook
2. Static type-checking
3. Non-exception Failures(非"异常"型错误)
  3.1. 访问对象上不存在的属性
  3.2. 打错字...
  3.3. 忘记调用函数...
4. Types for Tooling
5. TypeScript compiler(tsc) 
  5.1. Emitting with Errors
6. Explicit Types
7. Erased Types、Downleveling
8. Strictness 
  8.1. noImplicitAny
  8.2. strictNullChecks

1. About this Handbook

Over 20 years after its introduction to the programming community, JavaScript is now one of the most widespread cross-platform languages ever created. Starting as a small scripting language for adding trivial interactivity to webpages, JavaScript has grown to be a language of choice for both frontend and backend applications of every size. While the size, scope, and complexity of programs written in JavaScript has grown exponentially, the ability of the JavaScript language to express the relationships between different units of code has not.Combined with JavaScript’s rather peculiar runtime semantics, this mismatch between language and program complexity has made JavaScript development a difficult task to manage at scale.

The goal of TypeScript is to be a static typechecker for JavaScript programs - in other words, a tool that runs before your code runs (static) and ensures that the types of the program are correct (typechecked).

2. Static type-checking

代码语言:javascript复制
// Accessing the property 'toLowerCase'
// on 'message' and then calling it
message.toLowerCase();
// Calling 'message'
message();

The behavior of each operation depends entirely on what value we had in the first place.

  • Is message callable?
  • Does it have a property called toLowerCase on it?
  • If it does, is toLowerCase even callable?
  • If both of these values are callable, what do they return?

Ideally, we could have a tool that helps us find these bugs before our code runs. That’s what a static type-checker like TypeScript does. Static types systems describe the shapes and behaviors of what our values will be when we run our programs. A type-checker like TypeScript uses that information and tells us when things might be going off the rails.

3. Non-exception Failures(非"异常"型错误)

So far we’ve been discussing certain things like runtime errors - cases where the JavaScript runtime tells us that it thinks something is nonsensical. Those cases come up because the ECMAScript specification has explicit instructions on how the language should behave when it runs into something unexpected.

有一些错误 JS 会给出明确的异常

但是更多的情况是

一些 JS 语法上允许的东西,在业务系统中大概率的是导致bug的原因

3.1. 访问对象上不存在的属性

3.2. 打错字...

3.3. 忘记调用函数...

3.4. 逻辑错误...

4. Types for Tooling

TypeScript can catch bugs when we make mistakes in our code. That’s great, but TypeScript can also prevent us from making those mistakes in the first place.

5. TypeScript compiler(tsc)

代码语言:javascript复制
npm install typescript

5.1. Emitting with Errors

One thing you might not have noticed from the last example was that our hello.js file changed again. If we open that file up then we’ll see that the contents still basically look the same as our input file. That might be a bit surprising given the fact that tsc reported an error about our code, but this is based on one of TypeScript’s core values: much of the time, you will know better than TypeScript.

代码语言:javascript复制
tsc --noEmitOnError hello.ts

默认情况下,即使 tsc 编译报错,编译结果仍然会输出。如果附加 --noEmitOnError 参数,ts 编译报错的时候,将不再输出编译结果。

6. Explicit Types

TypeScript can tell us about other cases where we might have been called incorrectly.

  • Keep in mind, we don’t always have to write explicit type annotations. In many cases, TypeScript can even just infer (or “figure out”) the types for us even if we omit them.
    • Even though we didn’t tell TypeScript that msg had the type string it was able to figure that out. That’s a feature, and it’s best not to add annotations when the type system would end up inferring the same type anyway.

7. Erased Types、Downleveling

  • Type annotations aren’t part of JavaScript (or ECMAScript to be pedantic), so there really aren’t any browsers or other runtimes that can just run TypeScript unmodified. That’s why TypeScript needs a compiler in the first place - it needs some way to strip out or transform any TypeScript-specific code so that you can run it.
  • Type annotations never change the runtime behavior of your program.
  • By default TypeScript targets ES3, an extremely old version of ECMAScript. We could have chosen something a little bit more recent by using the --target flag.

8. Strictness

TypeScript has several type-checking strictness flags that can be turned on or off, and all of our examples will be written with all of them enabled unless otherwise stated. The --strict flag in the CLI, or "strict": true in a tsconfig.json toggles them all on simultaneously, but we can opt out of them individually. The two biggest ones you should know about are noImplicitAnyand strictNullChecks.

8.1. noImplicitAny

Recall that in some places, TypeScript doesn’t try to infer any types for us and instead falls back to the most lenient type: any. This isn’t the worst thing that can happen - after all, falling back to any is just the plain JavaScript experience anyway.

However, using any often defeats the purpose of using TypeScript in the first place. The more typed your program is, the more validation and tooling you’ll get, meaning you’ll run into fewer bugs as you code. Turning on the noImplicitAny flag will issue an error on any variables whose type is implicitly inferred as any.

8.2. strictNullChecks

By default, values like null and undefined are assignable to any other type. This can make writing some code easier, but forgetting to handle null and undefined is the cause of countless bugs in the world - some consider it a billion dollar mistake! The strictNullChecks flag makes handling null and undefined more explicit, and spares us from worrying about whether we forgot to handle null and undefined.

参考:

The TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/intro.html

0 人点赞