Skip to content

translate TS for JS Programmers to zh #118

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

cyishere
Copy link

No description provided.

@ghost
Copy link

ghost commented Aug 19, 2021

CLA assistant check
All CLA requirements met.

@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 is intended for JavaScript programmers
Short: TypeScript is intended for JS programmers
layout: docs
permalink: /zh/docs/handbook/typescript-in-5-minutes.html

oneline: Learn how TypeScript extends JavaScript

TypeScript has a unique relationship with JavaScript. TypeScript provides all the features of JavaScript, and there's an extra layer of content on top of it: TypeScript's type system.

For example, JavaScript provides the original types of the language, such as String and Number, but it does not check if you have used a consistent type when assigning values. TypeScript checks this.

This means that your existing Working JavaScript code is also TypeScript code. The biggest benefit of TypeScript is that it highlights unexpected behavior in your code and reduces the chance of bugs.

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

Inferred type (Types by Inference)

TypeScript understands the JavaScript language, and in many cases it can generate types for you. For example, when you create a variable and give it a specific value, TypeScript takes the type of that value as the type of the variable.

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

By understanding how JavaScript works, TypeScript can build a type system. This type of system not only accepts JavaScript code, but also has a type. This provides your code with a type system that defines the type without adding additional characters. That's how TypeScript knows in the example abovehelloworldThe variable is onestringThe principle of the type.

You might be writing JavaScript using Visual Studio Code and using the editor's auto-complement feature. Visual Studio Code is grounded with TypeScript, which makes it easier to work with JavaScript.

Defining Types

In JavaScript you can use a wide variety of design patterns. However, some design patterns can make it difficult to automatically infer types (for example, using dynamic planning patterns). To suit this, TypeScript supports the extension of the JavaScript language. This extension provides space for "you tell TypeScript what type to use."

For example, create an object that has one containedname: stringandid:numberThe type of inference of . You can write this way:

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

You can use oneinterfaceDeclaration to clearly describe the shape of the object (shape):

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

After that you can follow the new oneinterfacethe pattern of to declare the JavaScript object by using after the variable declaration: TypeNameSyntax: (will.)TypeNameReplace withinterfacename)

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

If the object you provide doesn't match the interface you provide, TypeScript warns you:

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

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

Because JavaScript supports class and object-oriented programming, TypeScript also supports it. You can use interface declarations for 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 annotate the form parameters and returned values of the function using interface:

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

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

There is already a small set of original types available in JavaScript:boolean(布尔值)bigintnullnumber(Value),string(string),symbolandundefinedThese you can use in interface. TypeScript extends this list to include more, such as:any(anything is allowed),unknown(make sure someone uses this type and declares what it is),never(This type is almost impossible to occur) andvoid(A function returns.)undefinedor do not return a value).

You'll see two build types of syntax:Interfaces and Types。 You should be inclined to use itinterface。 Use when you have special needstype

Composing Types

In TypeScript, you can create complex types by combining simple types. There are two popular ways to combine: unions and generics.

Unions

Using unions, you can declare a type as one of several types. For example, you can put onebooleanThe type is described astrueorfalseOne:

type MyBool = true | false;

_note:_If you hover over itMyBoolabove, you will see it classified asbooleantype. This is a property of the Structural Type System. Here's more on this.

A popular use case for union types is to describe a value that is allowed to be a groupstringornumberLiteral typeOne of them:

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

Union types also provide a way to handle different types. For example, you might have a function that accepts onearrayOr onestringAs an argument:

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

To know the type of a variable, usetypeof:

Type Predicate
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 based on whether the arguments passed in to it are strings or arrays:

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

Generics

Generics provide variables for types. A common example is arrays. An array that does not use generics can contain anything. An array that uses generics can describe the values contained in the array.

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

You can declare your own type using generics:

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

// 这行代码是一个快捷方式,它告诉了 TypeScript
// 有一个名为`backpack`的常量,且不用担心它来自哪里
declare const backpack: Backpack<string>;

// object 是一个字符串,因为我们在上面声明了这个变量是属于 Backpack 的
// 而在上面,Backpack 被指定为字符串了
const object = backpack.get();

// 由于 backpack 变量是一个字符串,你不能把数字传递给 add 函数
backpack.add(23);

Structural Type System

One of the core principles of TypeScript is that type checks focus on what values have_Form_above. This is sometimes referred to as "duck typeing" or "structural typing".

In a structural type system, two objects are considered to have the same type if they have the same pattern.

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

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

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

pointVariables are never declared asPointtype. However, TypeScript is compared during type checkingpointandPointthe form of . They are in the same shape, so the code passes the check.

Shape-matching requires only a portion of the field in the object to match.

// @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); // logs "12, 26"

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

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

There is no difference in how classes and objects match patterns:

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

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}
// ---cut---
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); // logs "13, 56"

If an object or class has all the necessary properties, TypeScript says they match, regardless of the details of the implementation.

Next

These are a brief overview of the syntax and tools used in everyday TypeScript. From here, you can:

Generated by 🚫 dangerJS against 911ab70

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.

1 participant