-
Notifications
You must be signed in to change notification settings - Fork 130
translate to simplified chinese #220
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
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.md
layout: docs permalink: /zh/docs/handbook/2/everyday-types.html This is not an exhaustive list, and subsequent chapters will describe more ways to name and use other types. As we look at the types themselves, we'll also see where they can be referenced to form new structures. These core building blocks later form more complex types. string ,number and boolean string 、number and boolean 。Each has a corresponding type in TypeScript. As you would expect, if you use JavaScript for these types of values typeof operator and you see these same names:[1, 2, 3] Such an array type can use syntax number[] , this syntax works for any type (eg string[] is an array of strings, and so on).You may also see it written as Array<number> , they mean the same thing.We'll learn more about when we learn generics T<U> Knowledge of grammar.any , whenever you don't want a particular value to cause a type check error.any , you can access any of its properties (will become any type), call it like a function, assign it to it any type of value (or from any type value), or any value that is syntactically legal:any Types are very useful.any Type.any It is not type-checked.Use compiler flags noImplicitAny Remove any implicit any for an error.const 、var or let When declaring a variable, you can optionally add a type annotation to explicitly specify the type of the variable:Whenever possible, TypeScript will try to automatic deduce The type in the code. For example, the type of a variable is inferred from the type of its initializer: If you're just starting out, you should consider experimenting with fewer use of type annotations – you might be surprised that TypeScript requires very little content to fully understand what's going on. TypeScript allows you to specify the types of input and output values for a function. The parameter type comment follows the parameter name: The return type annotation appears after the parameter list: return The statement infers the return type of the function.The type annotation in the example above does not change anything. Some codebases explicitly specify the return type for documentation purposes to prevent accidental changes or just for personal preference. Promise Type:When a function appears where TypeScript can make it clear how to call it, the function's parameters automatically specify the type. s There are no type annotations, TypeScript is also used forEach The type of the function is determined as well as the inferred array type s type.Later, we'll see more examples of how the context in which a value appears affects its type. This refers to almost any JavaScript value with any property! To define an object type, we only need to list its properties and its type. x and y ) to annotate the parameter, both of which are properties number Type.You can use it "," or ";" to separate the attributes, and the last separator is optional.If you do not specify a type, it is assumed to be any 。To do this, add after the property name "?" :undefined Instead of runtime errors.Therefore, when you read from an optional property, you must check before using it undefined 。Now that we know how to write some types, it's time to start in a fun way combination They too. A union type is a type formed by two or more other types and a representation can be one of these types Any kind The value of the type. We refer to each of these types as union member。 If you Yes A value of the union type, how do you use it? For example, if you have a federated type string | number , you cannot use only for string Method:This occurs when TypeScript can infer a more specific value type from the code structure shrink Range. string The value of the type is typeof The value is "string" :Array.isArray Function like this:else branches, we don't need to do anything special - if x No string[] , then it must be string 。For example, both arrays and strings have one slice Method.If each member of the union has a property in common, you can use that property without narrowing the scope: But often you want to easily use the same type multiple times and refer to it by a name. The syntax for type aliases is: For example, a type alias can name a union type: 版本 。When you use an alias, it is as if you had written an alias type. In other words, this code may looks Illegal, but according to TypeScript it is okay because both types are aliases of the same type: TypeScript only cares about what we pass on printCoord of the value structure - It only cares if it has the expected properties.Caring only about the structure and functionality of a type is what we call TypeScript Structure type The reason for the system. almost interface All features are available in type , the key difference is that types cannot be reopened (assigned or created) to add new properties, while interfaces are always extensible.interface until you need to use it type features in .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 。.tsx file), it is equivalent to:This rule prevents 不可能 of coercion, such as:If this happens, you can use two assertions, the first is any (or unknown , which we'll cover later), and then the type required:string and number In addition, we can also reference at the type location specific Strings and numbers.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. 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 .For example, if you write code like this: 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.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.null and undefined 。strictNullChecks Options.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 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:! (non-null assertion operator (suffix.)! ))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 :null or undefined , use only ! Very important.Although we won't delve into it here. BigInt :Symbol() To create a globally unique reference: |
Interface |
Type |
---|---|
扩展接口
|
通过交集扩展类型
|
向现有接口添加新字段
|
类型创建后不能更改
|
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
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 generated null
。
// @errors: 2352
const x = "hello" as number;
declare const expr: any;
type T = { a: 1; b: 2; c: 3 };
// ---分割---
const a = expr as any as T;
let changingString = "Hello World";
changingString = "Olá Mundo";
// 因为 `changingString` 可以表示任何可能的字符串,这就是 TypeScript 在类型系统中描述它的方式
changingString;
// ^?
const constantString = "Hello World";
// 因为 `constantString` 只能表示 1 个可能的字符串,所以它有一个文字类型表示
constantString;
// ^?
// @errors: 2322
let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";
// @errors: 2345
function printText(s: string, alignment: "left" | "right" | "center") {
// ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}
// @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"'
declare const someCondition: boolean;
// ---分割---
const obj = { counter: 0 };
if (someCondition) {
obj.counter = 1;
}
// @errors: 2345
declare function handleRequest(url: string, method: "GET" | "POST"): void;
// ---分割---
const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);
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 未定义
)strictNullChecks
off (Off严格的空检查
)strictNullChecks
on (enables strict null checking)function doSomething(x: string | null) {
if (x === null) {
// 没做什么
} else {
console.log("Hello, " + x.toUpperCase());
}
}
function liveDangerously(x?: number | null) {
// 没有错误
console.log(x!.toFixed());
}
bigint
(Large integer)// @target: es2020
// 通过 BigInt 函数创建 bigint
const oneHundred: bigint = BigInt(100);
// 通过文字语法创建 BigInt
const anotherHundred: bigint = 100n;
symbol
// @errors: 2367
const firstName = Symbol("name");
const secondName = Symbol("name");
if (firstName === secondName) {
// 永远不可能发生
}
@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.