Skip to content
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 TS for JS Programmers.md in zh-CN #159

Merged
merged 1 commit into from
Sep 22, 2022

Conversation

awxiaoxian2020
Copy link
Contributor

No description provided.

@github-actions
Copy link
Contributor

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

Translation of TS for JS Programmers.md

title: TypeScript for JavaScript programmers
short: TypeScript for JS programmers
layout: docs
permalink: /zh/docs/handbook/typescript-in-5-minutes.html

oneline: Learn TypeScript extensions to Javascript

TypeScript has an unusual relationship with JavaScript. TypeScript provides all the features of JavaScript and adds a layer to them: TypeScript's type system.

For example, JavaScript provides something such as string and number Such a primitive type, but it does not check whether you match the type when assigning. TypeScript provides such functionality.

This means that your existing well-functioning JavaScript code is also TypeScript code. The main benefit of TypeScript is that it checks for unexpected behavior in your code, reducing the chance of errors.

This tutorial provides a brief overview of TypeScript, focusing on its type system.

Type inference

TypeScript recognizes the JavaScript language and, in many cases, infers types. For example, when you create a variable and assign it to a specific value, TypeScript uses that value as its type.

let helloWorld = "Hello World";
//  ^?

By perceiving how JavaScript works, TypeScript can build a type system that accepts JavaScript code but has types. This type system makes it unnecessary for us to add extra characters to explicitly specify the type. In the example above, TypeScript knows that way helloWorld be string type.

You've probably written JavaScript in Visual Studio Code and used the editor's autocomplete feature. Visual Studio Code uses TypeScript's engine to make it easier to work with JavaScript.

Defines the type

You can use a variety of design patterns in JavaScript. However, certain design patterns make it difficult to automatically infer types (for example, patterns that use dynamic programming). In order for type inference to cover these situations, TypeScript supports extending the JavaScript language, which lets TypeScript know how to infer types.

For example, to create an object with an inferred type, the type includes name: string and id: numberYou can write:

const user = {
  name: "Hayes",
  id: 0,
};

You can use it interface Keyword sounds explicitly describe this object_The type of internal data_(Translator's note: hereinafter may be translated as "structure"):

interface User {
  name: string;
  id: number;
}

Then you can declare a conformist to this interface (interface) of JavaScript objects, used after variable declarations like : TypeName Syntax like this:

interface User {
  name: string;
  id: number;
}
// ---分割线---
const user: User = {
  name: "Hayes",
  id: 0,
};

If the supplied object does not match the provided interface, TypeScript warns:

// @errors: 2322
interface User {
  name: string;
  id: number;
}

const user: User = {
  username: "Hayes",
  id: 0,
};

Since JavaScript supports class and object-oriented programming, TypeScript also supports it. You can use interface declarations with classes:

interface User {
  name: string;
  id: number;
}

class UserAccount {
  name: string;
  id: number;

  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}

const user: User = new UserAccount("Murphy", 1);

You can use the interface to annotate the parameters and return the values to the function:

// @noErrors
interface User {
  name: string;
  id: number;
}
// ---分割线---
function getAdminUser(): User {
  //...
}

function deleteUser(user: User) {
  // ...
}

There are already some primitive types available in JavaScript:booleanbigintnullnumberstringsymbol and undefined, they can all be used in interfaces. TypeScript expands this list to include more content, for example any (any type allowed),unknown (make sure that the person using this type declares what the type is), never (This type cannot happen) and void (Returns.) undefined or a function that does not have a return value).

There are two syntaxes for build types: Interfaces and types。 You should prefer interface。 Use when specific features are required type

Combination type

With TypeScript, you can create complex types by combining simple types. There are two popular ways to do this: union and generics.

united

With union, you can declare a type that can be one of many types. For example, you can boolean The type is described as true or false

type MyBool = true | false;

_Note:_If you hover over it MyBool , you will see that it is classified as boolean。 This is a property of the structured type system. More detailed information is available below.

A popular use of the union type is description string or number targetLiteralThe legal value of .

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

Federation also provides a way to handle different types of work. For example, there might be a function handling array or string

function getLength(obj: string | string[]) {
  return obj.length;
}

To understand the type of variable, use typeof

type Inferred statements
string typeof s === "string"
number typeof n === "number"
boolean typeof b === "boolean"
undefined typeof undefined === "undefined"
function typeof f === "function"
array Array.isArray(a)

For example, you can have a function return different values depending on whether you are passing a string or an array:

function wrapInArray(obj: string | string[]) {
  if (typeof obj === "string") {
    return [obj];
//          ^?
  }
  return obj;
}

Generics

Generics provide variables for types. A common example is an array. Arrays without generics can contain anything. Arrays with generics can describe the values that the array contains.

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

You can declare yourself a type that uses generics:

// @errors: 2345
interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}

// 这一行是一个简写,可以告诉 TypeScript 有一个常量,叫做`backpack`,并且不用担心它是从哪
// 里来的。
declare const backpack: Backpack<string>;

// 对象是一个字符串,因为我们在上面声明了它作为 Backpack 的变量部分。
const object = backpack.get();

// 因为 backpack 变量是一个字符串,不能将数字传递给 add 函数。
backpack.add(23);

Structural type system

A core principle of TypeScript is type checking focuses on the.) shape that values have)。 This is sometimes called a "duck type" or "structural typing."

In a structured type system, two objects are considered to be of the same type if they have the same structure.

interface Point {
  x: number;
  y: number;
}

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}

// 打印 "12, 26"
const point = { x: 12, y: 26 };
logPoint(point);

point The variable is never declared as Point Type. However, in type checking, TypeScript will point Structure with PointStructure comparison. They have the same structure, so the code passes.

Structure matching only requires matching a subset of the object's fields.

// @errors: 2345
interface Point {
  x: number;
  y: number;
}

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}
// ---cut---
const point3 = { x: 12, y: 26, z: 89 };
logPoint(point3); // 打印 "12, 26"

const rect = { x: 33, y: 3, width: 30, height: 80 };
logPoint(rect); // 打印 "33, 3"

const color = { hex: "#187ABF" };
logPoint(color);

There is no difference between how classes and objects determine the structure:

// @errors: 2345
interface Point {
  x: number;
  y: number;
}

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}
// ---分割线---
class VirtualPoint {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

const newVPoint = new VirtualPoint(13, 56);
logPoint(newVPoint); // 打印 "13, 56"

If the object or class has all the required properties, TypeScript indicates that they match, regardless of its implementation details.

Next

This is a brief overview of the syntax and tools used in typeScript in general. See:

Generated by 🚫 dangerJS against f18438c

@awxiaoxian2020
Copy link
Contributor Author

@Kingwl PTAL if you have spare time.

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.

Looks good! Thanks for your work!

@Kingwl
Copy link
Contributor

Kingwl commented Sep 22, 2022

LGTM

@github-actions github-actions bot merged commit 028e122 into microsoft:main Sep 22, 2022
@github-actions
Copy link
Contributor

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

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.

2 participants