-
Notifications
You must be signed in to change notification settings - Fork 132
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
translate to simplified chinese #220
base: main
Are you sure you want to change the base?
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 Everyday Types.mdtitle: Common types oneline: "The language primitives."In this chapter, we will introduce some of the most common types of values in JavaScript code and explain the methods that describe the corresponding types in TypeScript. Types can also appear in many place, not just type annotations. We'll start by reviewing the most basic and common types you might encounter when writing JavaScript or TypeScript code. Basic type:
|
Interface |
Type |
---|---|
扩展接口
|
通过交集扩展类型
|
向现有接口添加新字段
|
类型创建后不能更改
|
You'll learn more about these concepts in later chapters, so don't worry if you can't understand all of them right away.
- Prior to TypeScript 4.2, type aliases were named possible appears in the error message, sometimes in place of an equivalent anonymous type (which may or may not be ideal). The interface will always be named in the error message.
- Type aliases may not participateDeclarations merge, but interfaces can。
- Interfaces can only be used to Declare the shape of an object and cannot rename the base type。
- The interface name will always In its original form In the error message, however only Appears only when used by name.
Most of the time, you can choose according to your personal preference, and TypeScript will tell you if you need other types of declarations. If you want a heuristic, use interface
until you need to use it type
features in .
Type Assertions
Sometimes you have information about value types that TypeScript can't understand.
For example, if you are using document.getElementById
, TypeScript only knows that this will return some sort of thing HTMLElement
, but you probably know that your page will always have one with a given ID HTMLCanvasElement
。
In this case, you can use Type assertions to specify a more specific type:
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
Like type annotations, type assertions are removed by the compiler and do not affect the behavior of the code when it runs.
You can also use angle bracket syntax (unless the code is located in .tsx
file), it is equivalent to:
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
Note: Because type assertions are removed at compile time, there are no runtime checks related to type assertions.
If the type assertion is incorrect, no exception OR is generatednull
。
TypeScript only allows type assertion conversion Be more specific or Not too specific The type version.
This rule prevents 不可能
of coercion, such as:
// @errors: 2352
const x = "hello" as number;
Sometimes, this rule can be too conservative and does not allow for more complex enforcement that may be effective.
If this happens, you can use two assertions, the first is any
(or unknown
, which we'll cover later), and then the type required:
declare const expr: any;
type T = { a: 1; b: 2; c: 3 };
// ---分割---
const a = expr as any as T;
Literal Types
In addition to generic types string
and number
In addition, we can also reference at the type location specific Strings and numbers.
One way to think about this is to consider how JavaScript declares variables in different ways. var
and let
Both allow changing the contents saved within the variable instead const
is not allowed.
This is reflected in how TypeScript creates types for text.
let changingString = "Hello World";
changingString = "Olá Mundo";
// 因为 `changingString` 可以表示任何可能的字符串,这就是 TypeScript 在类型系统中描述它的方式
changingString;
// ^?
const constantString = "Hello World";
// 因为 `constantString` 只能表示 1 个可能的字符串,所以它有一个文字类型表示
constantString;
// ^?
On its own, text types are not very valuable:
// @errors: 2322
let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";
A variable that can only have one value is not very useful!
But by text combination Together, you can express more useful concepts - for example, functions that accept only a specific set of known values:
// @errors: 2345
function printText(s: string, alignment: "left" | "right" | "center") {
// ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
Numeric literal types work the same way:
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}
Of course, you can combine them with non-text types:
// @errors: 2345
interface Options {
width: number;
}
function configure(x: Options | "auto") {
// ...
}
configure({ width: 100 });
configure("auto");
configure("automatic"); // error: Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'
There is another type of text: the Boolean type.
There are only two Boolean text types, and as you might guess, they are true
and false
Type.
type boolean
In itself, it's really just union true | false
alias of .
Literal Inference (literal reasoning)
When you initialize a variable with an object, TypeScript assumes that the object's properties might change values later.
For example, if you write code like this:
declare const someCondition: boolean;
// ---分割---
const obj = { counter: 0 };
if (someCondition) {
obj.counter = 1;
}
TypeScript does not assume will 1
Assigned to previously had 0
The field is wrong.
Another way of saying it is obj.counter
Must have number
type, instead 0
, because the type is used to determine Read and write Behavior.
The same applies to strings:
// @errors: 2345
declare function handleRequest(url: string, method: "GET" | "POST"): void;
// ---分割---
const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);
In the example above,req.method
is inferred as string
Instead of "GET"
。 Because the code can be created req
and invoke handleRequest
This can be evaluated like "GUESS"
Such a new string is assigned to req.method
, so TypeScript thinks this code is wrong.
There are two ways to solve this problem.
-
You can change the inference by adding a type assertion in either place:
declare function handleRequest(url: string, method: "GET" | "POST"): void; // ---分割--- // Change 1: const req = { url: "https://example.com", method: "GET" as "GET" }; // Change 2 handleRequest(req.url, req.method as "GET");
Change 1 means "I intend to make
req.method
Always have Text type"GET"
", thus preventing possible aftermath"GUESS"
Assigned to the field.
Change 2 means "I know for other reasons."req.method
The value is"GET"
。 -
You can use it
as const
To convert an entire object to type literal:declare function handleRequest(url: string, method: "GET" | "POST"): void; // ---分割--- const req = { url: "https://example.com", method: "GET" } as const; handleRequest(req.url, req.method);
as const
The function of the suffix is similar to const
, but for the type system, make sure that all properties are assigned as literal types, not like them string
or number
Such a more generic version.
null
and undefined
( 空
and 未定义
)
JavaScript has two primitive values to represent values that do not exist or are not initialized:null
and undefined
。
TypeScript has two corresponding ones with the same name type 。 How these types behave depends on whether you have enabled them strictNullChecks
Options.
strictNullChecks
off (Off严格的空检查
)
Shut down strictNullChecks
After that, you can still access normally as possible null
or undefined
and can be valued null
and undefined
Assigned to any type of property.
This is similar to how languages without null checking (e.g. C#, Java) behave.
Lack of checking for these values is often a major source of error; If it works in the codebase, we always recommend opening it strictNullChecks
。
strictNullChecks
on (enables strict null checking)
enable strictNullChecks
After that, the value is null
or undefined
, you need to test the values before using methods or properties on them.
Just like checking before using optional attributes undefined
Again, we can use narrowing to check what might be null
Value:
function doSomething(x: string | null) {
if (x === null) {
// 没做什么
} else {
console.log("Hello, " + x.toUpperCase());
}
}
Non-null Assertion Operator (Postfix !
(non-null assertion operator (suffix.)!
))
TypeScript also has a special syntax that can be removed from types null
and undefined
without any explicit checking.
Write after any expression !
It is actually a type assertion indicating that the value is not null
or undefined
:
function liveDangerously(x?: number | null) {
// 没有错误
console.log(x!.toFixed());
}
Just like other types of assertions, this does not change the runtime behavior of the code, so when you know the value No for null
or undefined
, use only !
Very important.
Enums (enumeration)
Enumerations are a feature added to JavaScript by TypeScript that allows you to describe a value, which can be one of a set of possible named constants. Unlike most TypeScript features, this No JavaScript is added at the type level, but instead added to the language and runtime stuff. Therefore, you should be aware of the presence of the feature, but unless you are sure, it may be postponed. You can find it inEnumerate reference pagesRead more about enumerations.
Less Common Primitives
It is still necessary to explain the other basic types represented in JavaScript in the type system.
Although we won't delve into it here.
bigint
(Large integer)
Starting with ES2020, there is a basic type in JavaScript for very large integers,BigInt
:
// @target: es2020
// 通过 BigInt 函数创建 bigint
const oneHundred: bigint = BigInt(100);
// 通过文字语法创建 BigInt
const anotherHundred: bigint = 100n;
You can find it in TypeScript 3.2 release notes Learn more about BigInt.
symbol
There is a basic type in JavaScript for passing functions Symbol()
To create a globally unique reference:
// @errors: 2367
const firstName = Symbol("name");
const secondName = Symbol("name");
if (firstName === secondName) {
// 永远不可能发生
}
You can find it in Symbols reference pageLearn more about them.
@microsoft-github-policy-service agree |
Please Move On https://github.com/ts-zh-docs/TypeScript-zh-Website. |
Translation: Translate Everyday Types.md file into Simplified Chinese.