Skip to content

Translate Basics Into Chinese #130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 14, 2022
Merged

Translate Basics Into Chinese #130

merged 1 commit into from
Jul 14, 2022

Conversation

Chorer
Copy link
Contributor

@Chorer Chorer commented Dec 8, 2021

No description provided.

@ghost
Copy link

ghost commented Dec 8, 2021

CLA assistant check
All CLA requirements met.

@github-actions
Copy link
Contributor

github-actions bot commented Dec 8, 2021

Thanks for the PR!

This section of the codebase is owned by @Kingwl - if they write a comment saying "LGTM" then it will be merged.

@github-actions
Copy link
Contributor

github-actions bot commented Dec 8, 2021

Translation of Basics.md

title: Basic
layout: docs
permalink: /zh/docs/handbook/2/basic-types.html
oneline: "The first step in learning TypeScript: Basic types."
preamble: >

Welcome to the first page of the manual. If this is your first exposure to TypeScript - you may need to read it first'Entry'The guide

Each value in JavaScript exhibits a series of behaviors as we perform different operations.

This sounds abstract, and look at the following example and consider the variables message Possible actions.

// 访问 message 的 toLowerCase 方法并调用它
message.toLowerCase();

// 调用 message 函数
message();

If we split the process, the first line of code is accessed message target toLowerCase method and call it;

The second line of code attempts to call directly message function.

But let's assume, we don't know message value -- This is a very common case, we can't know the final result exactly from the code above.
The result of each operation depends entirely on the operation message The initial value of .

  • message Can I call it?
  • It has toLowerCase Property?
  • If there is this property, then toLowerCase Can I call it?
  • If message And its properties are callable, so what are the returns?

When writing JavaScript code, the answers to these questions often need to be kept in our heads, and we have to pray that we have all the details.

hypothesis message This is defined as:

const message = "Hello World!";

You may easily guess if executed message.toLowerCase(), we'll get a string where all the letters are lowercase.

What if you execute the second line of code?

You must have guessed that JavaScript would throw an exception:

TypeError: message is not a function

If only such a mistake could be avoided.

When we execute the code, the JavaScript runtime calculates the valuetype What behaviors and functions of this type determine what actions to take.

That's what the code above throws TypeError Cause -- It indicates the string "Hello World!" Cannot be called as a function.

For example string or number Such a primitive type that we can pass typeof Operators calculate their type at runtime.

But for a type like a function, there is no corresponding runtime mechanism to calculate the type.

For example, look at the following function:

function fn(x) {
  return x.flip();
}

From the code can besee, only if there is one with flip This function works only when the property is an object, but JavaScript cannot pass this information in a way that we can check when the code executes.

Let pure JavaScript tell us fn The only way to do anything when a particular parameter is given is to actually call it fn function.

This behavior makes it difficult to make relevant predictions before code executes, and it also means that when we write code, it is difficult to figure out what the code will do.

From this point of view, so-calledtypeIt's actually a description of what values can be safely passed on to fnWhat value can cause an error.

JavaScript only provides dynamic types -- executing code -- before you know what's going to happen.

Then you might want to use an alternative, using a static type system, to predict the behavior of your code before it actually executes.

Static type check

Remember when we threw the string as a function call TypeError Is that wrong?

A lot of peopleI don't want to see any errors when you execute code -- after all, these are bugs!

When we write new code, we also try to avoid introducing new bugs.

If we just add a little code, save the file, rerun the code, and then immediately see the error, then we might be able to quickly locate the problem -- but that's only a few after all.

We may not have thoroughly and thoroughly tested it so that we didn't find any potential errors!

Or, if we're lucky enough to find this error, we might end up with a massive refactoring and a lot of different code.

Ideally, we have a tool to find bugs before code executes.

And that's exactly what static type inspectors like TypeScript do.

Static type systemDescribes the structure and behavior of program runtime values.

Static type inspectors like TypeScript take advantage of the information provided by the type system and let us know when things go wrong.

// @errors: 2349
const message = "hello!";

message();

Run the previous example with TypeScript, which throws an error before we execute the code.

Non-exception failure

So far, we've been talking about runtime errors -- JavaScript runtimes tell us that it feels like there's an exception somewhere.

These exceptions can be thrown because ECMAScript specification Behaviors that should be performed against exceptions are clearly defined.

For example, the specification states that an attempt to invoke something that cannot be called should throw an error.

Maybe this sounds like "obvious behavior" and you'll feel that an error is thrown when accessing properties that don't exist on the object.

On the contrary, JavaScript behaves differently than we expected, returning values undefined

const user = {
    name: 'Daniel',
    age: 26,
};
user.location;       // 返回 undefined

Ultimately, we need a static type system to tell us which code is marked as wrong in this system -- even if it is "valid" JavaScript code that doesn't immediately cause errors.

In TypeScript, the following code throws an error that states location There is no definition:

// @errors: 2339
const user = {
  name: "Daniel",
  age: 26,
};

user.location;

While sometimes this means you need to weigh what you're saying, our goal is to find more legitimate bugs in the program.

TypeScript does captureA lotLegitimate bugs:

For example, spelling mistakes:

// @noErrors
const announcement = "Hello World!";
 
// 你需要花多久才能注意到拼写错误?
announcement.toLocaleLowercase();
announcement.toLocalLowerCase();
 
// 实际上正确的拼写是这样的……
announcement.toLocaleLowerCase();

Functions not called:

// @noUnusedLocals
// @errors: 2365
function flipCoin() {
  // 应该是 Math.random()
  return Math.random < 0.5;
}

Or a basic logical error:

// @errors: 2367
const value = Math.random() < 0.5 ? "a" : "b";
if (value !== "a") {
  // ...
} else if (value === "b") {
// 永远无法到达这个分支
}

Type tool

TypeScript can catch bugs when our code goes wrong.

That's good, but more crucially, it isalsoAbility to prevent errors in our code from the start.

The type inspector can check by obtaining information whether we are accessing the correct property on a variable or other property.

Once it gets this information, it can also prompt you for the properties you might want to access.

This means that TypeScript can also be used to edit code. When we enter it in the editor, the core type checker provides error information and code complements.

A typical example is the role of TypeScript at the tool level.

// @noErrors
// @esModuleInterop
import express from "express";
const app = express();

app.get("/", function (req, res) {
  res.sen
//       ^|
});

app.listen(3000);

TypeScript is powerful at the tool level, far more than code complements and error message prompts when spelling.

TypeScript-enabled editors automatically fix errors with quick fixes to refactor code that is easy to organize. It also has effective navigation capabilities that allow us to jump to a variable definition or find all references to a given variable.

All of these features are built on the type inspector and are cross-platform, thereforeYour favorite editor probably also supports TypeScript

TypeScript compiler - tsc

We've been talking about type checkers, but we haven't used them yet.

It's time to work with our new friend, the TypeScript compiler tsc I'm dealing with it.

First, install via npm.

npm install -g typescript

This will install the Compiler for TypeScript globally tsc。 If you prefer to install in a local node_modules folder, you may need npx or similar tools to run the tsc instruction easily.

Now, let's create an empty folder and try to write the first TypeScript program:hello.ts

// 和世界打个招呼
console.log('Hello world!');

Note that this line of code doesn't have any extra decoration, it looks exactly like the "hello world" program written with JavaScript.

Now, let's run typescript The installation package comes with it tsc The instruction performs a type check.

tsc hello.ts

see!

Wait, "look."What thethis?

We're running tsc instructions, but nothing happened!

Yes, after all, there are no type errors in this line of code, so of course you don't see the output of error messages in the console.

But check again -- we actually got an outputfile

If we look at the current directory, we will find that in addition to hello.ts There is one more in the file hello.js file.

whereas hello.js The file is tsc compileorconversion hello.ts The pure JavaScript file that is output after the file.

If checked hello.js The contents of the file, we can see that the TypeScript compiler is finished .ts What is produced after the document:

// 和世界打个招呼
console.log('Hello world!');

In this example, TypeScript has little to translate, so the code before and after translation looks exactly the same.

The compiler always tries to produce clear, readable code that looks like it was written by a normal developer.

While this is not easy, TypeScript always indents, focuses on cross-line code, and tries to keep comments.

What if we deliberately introduce a type check error?

Let's rewrite it hello.ts

// @noErrors
// This is an industrial-grade general-purpose greeter function:
function greet(person, date) {
  console.log(`Hello ${person}, today is ${date}!`);
}

greet("Brendan");

If we execute again tsc hello.ts, you'll notice that the command line throws an error!

Expected 2 arguments, but got 1.

TypeScript tells us that we passed less than one parameter to greet Function -- should have passed in the argument.

So far, we've written standard JavaScript code, but type checking can still uncover problems in our code.

Thanks TypeScript!

Documents are still produced at the time of error

One thing you may not have noticed in the example above is ours hello.js The file has been changed again.

If we open this file, we will find that the contents are the same as the contents of the files entered.

This may come as a bit unexpected, after all tsc I reported it wrong just now. But this result is actually related to TypeScript's core principle: Most of the time,youKnow the code better than TypeScript.

Again, type checking of code limits the kind of programs that can be run, so the type inspector makes trade-offs to determine which code is acceptable.

Most of the time, it's okay, but sometimes these checks can get in the way.

For example, imagine that you are now migrating JavaScript code to TypeScript code and have produced many type check errors.

Finally, you have to spend time resolving the error thrown by the type inspector, but the problem is that the original JavaScript code itself is operational! Why can't you run them when you convert them to TypeScript code?

So TypeScript doesn't stand in your way.

Of course, over time, you may want to take more defensive action against mistakes, while also making TypeScript more aggressive.

In this case, you can turn it on noEmitOnError Compilation options.

Try to modify yours hello.ts file, and use parameters to run tsc directives:

tsc --noEmitOnError hello.ts

Now you'll find thathello.js No more changes have been made.

Explicit type

So far, we haven't told TypeScript person and date What is it.

Let's modify the code and tell TypeScript person It's one stringdata should be one Date object.

We'll pass, too date go to call toDateString method.

function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

What we do is give person and date Add toType annotationsdescription greet What type of argument should be accepted at the time of the call?

You can interpret this signature as "greet accept string Type personand Date Type date”。

With type annotations, TypeScript can tell us which cases are for greet The call to may be incorrect.

Like what......

// @errors: 2345
function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

greet("Maddison", Date());

Ha?

TypeScript error indicates a problem with the second parameter, but why?

You might be a little surprised because it's called directly in JavaScript Date() What is returned is string

On the other hand, through new Date() To construct one Date, you can return one as expected Date object.

Anyway, we can fix this error quickly:

function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
 
greet("Maddison", new Date());

Keep in mind that we don't always need to explicitly type annotations.

In many cases, TypeScript can be for us, even if type annotations are omittedinferred(or "clear") type.

let msg = "hello there!";
//  ^?

Even if we didn't tell TypeScript msg The type of is stringand it can figure it out for itself.

This is a feature, and it is best not to manually add type annotations when the type system is able to make type inferences correctly.

Note: The code information is shown in the code example above. If you mouse over the variable, the editor will have the same prompt.

The erase type

Let's take a look and pass tsc will be above greet What happens when a function is compiled into JavaScript:

// @showEmit
// @target: es5
function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

greet("Maddison", new Date());

Two changes were noted:

  1. our person and date The type annotation of the argument is missing.
  2. Our "template string" - using back quotes (`The string of the package -- becomes passed + A normal string stitched together.

To explain the second point later, let's look at the first change.

Type annotations are not part of JavaScript (or professional ECMAScript), so no browser or runtime can execute unprocessed TypeScript code directly.

That's why TypeScript needs a compiler first -- it needs to be compiled to remove or convert TypeScript-specific code so that it can run on the browser.

Most typeScript-specific code is erased, and in this example, you can see that the code for type annotations is completely erased.

**Remember:**Type annotations never change the behavior of your program at runtime

demote

Another change above is our template string from:

`Hello ${person}, today is ${date.toDateString()}!`;

Is rewritten as:

"Hello " + person + ", today is " + date.toDateString() + "!";

Why is this happening?

Template strings are a new feature introduced by ECMAScript 2015 (or ECMAScript6, ES2015, ES6, etc.).

TypeScript can override code for higher versions of ECMAScript to earlier versions of code such as ECMAScript3 or ECMAScript5 (i.e. ES3 or ES5).

Code like this that downgrades an updated or "later" version of ECMAScript to an older or "lower" version is calleddemote

By default, TypeScript translates into ES3 code, which is a very old version of ECMAScript. We can use it target Options convert code to newer ECMAScript versions.

By using --target es2015 The parameters are compiled and we can get the target code for the 2015 version of ECMAScript, which means that the code can be executed in an environment that supports ECMAScript2015.

Therefore, run tsc --target es2015 hello.ts After that, we'll get the following code:

function greet(person, date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
greet("Maddison", new Date());

Although the default target code is ES3 syntax, most browsers now support ES2015.

Therefore, most developers can safely specify that the target code is ES2015 or higher, unless you need to focus on compatibility with some older browsers.

Strictness

Different users choose to use TypeScript's type inspector for different reasons.

Some users are looking for a looser, optional development experience, and they want type checking to work only on part of the code, while also enjoying the functionality provided by TypeScript.

This is also the development experience that TypeScript provides by default, the type is optional, and the loosest type is inferred to be used for potential null/undefined The value of the type is also not checked.

It's like tsc These default configurations ensure that your development process is not hindered, just as normal output files can still be made in the event of compilation errors.

If you are migrating existing JavaScript code, this configuration may just be appropriate.

On the other hand, most users prefer TypeScript to be able to examine code as quickly and as much as possible, which is why the language provides strict settings.

These strict settings convert static type checks from a mode of switching switches (for your code, either all or none at all) to a mode close to the dial.

The more you adjust it, the more TypeScript will check for you.

This may require additional work, but in the long run it is worth it, and it can lead to more thorough inspection as well as more sophisticated tools.

If possible, the new code base should always enable these strict configurations.

TypeScript has several strict settings related to type checking that can be turned on or off at any time, and the examples in our documentation are executed with all strict settings turned on without special instructions.

IN the CLI strict Configuration item, or tsconfig.json in "strict: true" Configuration items that allow you to turn on all strictness settings at once. But we can also turn a setting on or off individually.

Of all these settings, this is of particular concern noImplicitAny and strictNullChecks

noImplicitAny

Recall that in some of the previous examples, TypeScript did not infer the type for us, at which point the variable takes the broadest type:any。 It's not the worst thing -- after all, use it any The type is basically the same as pure JavaScript.

However, use any This is often contrary to the purpose of using TypeScript.

The more types your program uses, the more you gain on validation and tools, which means you'll encounter fewer bugs when coding.

enable noImplicitAny Configuration item, implicitly inferred in encounter any An error is thrown when a variable of the type is thrown.

strictNullChecks

By default,null and undefined Can be assigned to any other type.

This will make coding easier, but there are countless bugs around the world that you forget to deal with null and undefined Causes -- sometimes it doesbillions of dollars in losses

strictNullChecks Configure the items for processing null and undefined The process is more obvious to usNoworried about whether he wasforgetdispose null and undefined

Generated by 🚫 dangerJS against 0ec87ba

Copy link
Contributor

@Kingwl Kingwl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Chorer
Copy link
Contributor Author

Chorer commented Jul 13, 2022

@Kingwl What's wrong with the check ?

@orta
Copy link
Contributor

orta commented Jul 13, 2022

Probably worth trying a second time - I couldn't quite figure out why it would occasionally do this OSS-Docs-Tools/code-owner-self-merge#35

@Kingwl
Copy link
Contributor

Kingwl commented Jul 14, 2022

LGTM

@github-actions github-actions bot merged commit 9b35999 into microsoft:main Jul 14, 2022
@github-actions
Copy link
Contributor

Merging because @Kingwl is a code-owner of all the changes - thanks!

@Kingwl
Copy link
Contributor

Kingwl commented Jul 14, 2022

Cool! It works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants