-
Notifications
You must be signed in to change notification settings - Fork 128
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
Conversation
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. |
Translation of Basics.mdtitle: Basic 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 的 toLowerCase 方法并调用它
message.toLowerCase();
// 调用 message 函数
message(); If we split the process, the first line of code is accessed The second line of code attempts to call directly But let's assume, we don't know
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 const message = "Hello World!"; You may easily guess if executed 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 For example 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 Let pure JavaScript tell us 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 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 checkRemember when we threw the string as a function call 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 failureSo 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 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 // @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 toolTypeScript 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 - tscWe'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 First, install via npm. npm install -g typescript
Now, let's create an empty folder and try to write the first TypeScript program: // 和世界打个招呼
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 tsc hello.ts see! Wait, "look."What thethis? We're running 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 whereas If checked // 和世界打个招呼
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 // @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 Expected 2 arguments, but got 1. TypeScript tells us that we passed less than one parameter to 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 errorOne thing you may not have noticed in the example above is ours 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 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 tsc --noEmitOnError hello.ts Now you'll find that Explicit typeSo far, we haven't told TypeScript Let's modify the code and tell TypeScript We'll pass, too function greet(person: string, date: Date) {
console.log(`Hello ${person}, today is ${date.toDateString()}!`);
} What we do is give You can interpret this signature as " With type annotations, TypeScript can tell us which cases are for 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 On the other hand, through 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 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.
The erase typeLet's take a look and pass // @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:
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.
demoteAnother 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 Therefore, run function greet(person, date) {
console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
greet("Maddison", new Date());
StrictnessDifferent 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 It's like 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 Of all these settings, this is of particular concern
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
@Kingwl What's wrong with the check ? |
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 |
LGTM |
Merging because @Kingwl is a code-owner of all the changes - thanks! |
Cool! It works |
No description provided.