Skip to content

[ja translation] get started #46

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 2 commits into
base: main
Choose a base branch
from

Conversation

uraway
Copy link
Contributor

@uraway uraway commented Feb 27, 2021

ref: #3

diff: 41d811b

@github-actions
Copy link
Contributor

Thanks for the PR!

This section of the codebase is owned by @sasurau4, @Quramy, and @Naturalclar - if they write a comment saying "LGTM" then it will be merged.

@github-actions
Copy link
Contributor

Translation of TS for Functional Programmers.md

title: TypeScript for functional programmers
short: TS for functional programmers
layout: docs
permalink: /ja/docs/handbook/typescript-in-5-minutes-func.html

oneline: Learn TypeScript from a functional programming background

TypeScript allows Microsoft programmers to use traditional object-oriented programs on the Web
Try to introduce traditional object-oriented types into JavaScript to be able to deploy
It started with an attempt. As development progresses, typescript type systems
It has evolved to model code written by programmers.
As a result, the system is powerful, interesting, and complex.

This primer is an active student who wants to learn TypeScript.
For Haskell and ML programmers. The TypeScript type system
Learn how it differs from Haskell's type system.
In addition, typeScript modeling of JavaScript code
Unique features of type systems are also introduced.

Object-oriented programming is not discussed here.
In fact, typescript object-oriented programs are
It is very similar to that of other popular languages with program functions.

Premise

This primer assumes that you know:

  • How to program in JavaScript and its benefits
  • C-system language syntax

If you need to learn about the benefits of JavaScript,
JavaScript: The Good PartsRead on.
Have little but mutable values and pass by value
If you know how to write programs in a lexicalscope language,
You may be able to skip this book.
R4RS SchemeIs a good example.

The C++ Programming LanguageIs not
It's a good place to learn the syntax of C-style types. Not like C++,
TypeScript isstring xNotx: stringPut the type behind you, as shown.

Concepts not d't dinged in Haskell

Built-in types

JavaScript defines eight built-in types:

Type Description
Number IEEE 754 standard doubles
String Imutable UTF-16 String
BigInt Integers in arbitrary precision format
Boolean trueAndfalse
Symbol A unique value commonly used as a key
Null Value equivalent to Unit type
Undefined Similarly, a value equivalent to the Unit type
Object Values that are very similar to record structures

For details, please refer to the MDN page..

TypeScript has primitive types that correspond to built-in types:

  • number
  • string
  • bigint
  • boolean
  • symbol
  • null
  • undefined
  • object

Other important TypeScript types

Type Description
unknown Top-level type
never Lowest type
Object literals Example { property: Type }
void Designed for use as a return typeundefinedPartial type of
T[] Mutable array,Array<T>Can also be described
[T, T] a tuple that is fixed-length but mutable
(t: T) => U Function

Note:

  1. The syntax of the function contains the parameter name. This is very hard to get used to!

    let fst: (a: any, b: any) => any = (a, b) => a;
    
    // あるいはもっと正確に:
    
    let fst: <T, U>(a: T, b: U) => T = (a, b) => a;
  2. The object literal type syntax strictly reflects the value syntax of the object literal:

    let o: { n: number; xs: object[] } = { n: 1, xs: [] };
  3. [T, T]Is notT[]It is a partial type. This is different from Haskell, where tuples are not related to lists.

Boxed types

JavaScript has boxed types that are equivalent to primitive types.
The programmer has methods to associate with those types. In TypeScript,
the difference between them, such as primitive typesnumberand is a boxed typeNumber
reflects the difference between the two. Methods of boxed types are
therefore, boxed types are rarely required.

(1).toExponential();
// 上記は次と等しい
Number.prototype.toExponential.call(1);

When calling a method of numerical literals, to make the parser understand
Note that it must be enclosed in parentheses.

Progressive

TypeScript is always used whenever you don't know the type of an expression.anyUse types.
DynamicCompared toanyIt may be a great thing to call a type.
This is just disabling the type checker. Example:
without forming any value or value in any way.
any[]can be pushed to.

//  tsconfig.jsonで"noImplicitAny": falseの場合は、anys: any[]とします
const anys = [];
anys.push(1);
anys.push("oh no");
anys.push({ anything: "goes" });

AndanyMold expressions can be used anywhere:

anys.map(anys[1]); // oh no, "oh no"は関数ではありません

AlsoanyIs contagious — anyWhen initialized with a type expression,
And that variable.anyHave a type.

let sepsis = anys[0] + anys[1]; // どんな値でも入れることができます

TypeScriptanyTo generate an error when you generatetsconfig.jsonIn
"noImplicitAny": trueOr"strict": trueUse the .

Structural

Structural typeing is familiar to most functional programmers.
Haskell and many ML do not have structural types. The basic form is
Very simple:

// @strict: false
let o = { x: "hi", extra: 1 }; // ok
let o2: { x: string } = o; // ok

Here, the object literal{ x: "hi", extra: 1 }Is,
Literal type to match it{ x: string, extra: number }I have.
This type has all the properties that are required, and those properties are
Because it can be assigned to a type,{ x: string }can be assigned to .
The extra property does not interfere with the assignment, but rather the latter type.{ x: string }Of
Make it a partial type.

Named types simply name the type. For assignment purposes
The following is an alias for the typeOneand is an interface typeTwoand between
There is no difference. Bothp: stringHas a property. (But,
Type aliases are interfaces for recursive definitions and type parameters.
Behave differently. )

// @errors: 2322
type One = { p: string };
interface Two {
  p: string;
}
class Three {
  p = "Hello";
}

let x: One = { p: "hi" };
let two: Two = x;
two = new Three();

Unions

In TypeScript, the Union type is not tagged. In other words,
Haskell'sdataIt is not a distinguished Union like. But
You can use built-in tags and other properties to distinguish types in Union.

function start(
  arg: string | string[] | (() => string) | { s: string }
): string {
  // これはJavaScriptでは非常に一般的です
  if (typeof arg === "string") {
    return commonCase(arg);
  } else if (Array.isArray(arg)) {
    return arg.map(commonCase).join(",");
  } else if (typeof arg === "function") {
    return commonCase(arg());
  } else {
    return commonCase(arg.s);
  }

  function commonCase(s: string): string {
    // 最後に、文字列を別の文字列に変換します
    return s;
  }
}

stringArrayAndFunctionhas a built-in typed word.
The object type iselseit is useful to leave it for the purpose of
However, you can also generate unions that are difficult to distinguish at run time.
You can do. When you write new code
It is best to create only distinguishable Unions.

The following types have built-in ad fore languages:

Type Predicate
string typeof s === "string"
number typeof n === "number"
Bigint typeof m === "bigint"
boolean typeof b === "boolean"
symbol typeof g === "symbol"
undefined typeof undefined === "undefined"
function typeof f === "function"
array Array.isArray(a)
object typeof o === "object"

Functions and arrays are objects at run time, but they have their own ad noted
Note that you have.

Intersections

In addition to Union, TypeScript also has intersections:

type Combined = { a: number } & { b: string };
type Conflicting = { a: number } & { a: string };

Combinedis described as a single object literal type.
aAndbHas two properties: Intersection and Union are
If there is a conflict, it will be recursively processed.Conflicting.aIs,number & stringIt comes to.

Unit type

The Unit type is a primitive type partial type that has a strict single primitive value.
Have. For example, a string"foo"Is,"foo"It has a type.
JavaScript does not have a built-in Enum, so instead of a known string,
It is common to use sets. By string literal type Union,
TypeScript can type the following patterns:

declare function pad(s: string, n: number, direction: "left" | "right"): string;
pad("hi", 10, "left");

If necessary, the compiler may, for example,"foo"FromstringSuch as
Unit type to primitive type Extended — Convert to higher type — I will.
This happens when dealing with mutable values, and the use of mutable variables
may be hindered.

// @errors: 2345
declare function pad(s: string, n: number, direction: "left" | "right"): string;
// ---cut---
let s = "right";
pad("hi", 10, s); // error: 'string' is not assignable to '"left" | "right"'

Learn how errors occur:

  • "right": "right"
  • "right"is assigned to a mutable variable.stringBecause it is extended tos: stringIt comes to
  • stringIs not"left" | "right"Cannot be assigned to

scan be avoided by attaching type annotations to
This is at the same time"left" | "right"For variables that do not have a typesI'm 1000000000
I'm going to prevent it.

declare function pad(s: string, n: number, direction: "left" | "right"): string;
// ---cut---
let s: "left" | "right" = "right";
pad("hi", 10, s);

Haskell-like concept

Contextual type

TypeScript reveals variable declarations, and so on.
There are a number of places where types can be inferred:

let s = "I'm a string!";

However, for those who have used other C syntax languages,
Infer types even in places you don't think of:

declare function map<T, U>(f: (t: T) => U, ts: T[]): U[];
let sns = map((n) => n.toString(), [1, 2, 3]);

Above, before the callTAndUis not inferred.
n: numberIt comes to. In fact[1,2,3]With
T=numberAnd after reasoning,n => n.toString()Of
From the return typeU=stringinfer. By this
snsIs notstring[]will have a type.

Inference works in any order, but intellisense
It only works from left to right, so TypeScript uses arrays first.
mapNote that it is preferable to declare:

declare function map<T, U>(ts: T[], f: (t: T) => U): U[];

Contextual types are object literals and otherwisestringOrnumberAnd
It also works recursively for unit types that are inferred. Also
You can infer the type of return value from context:

declare function run<T>(thunk: (t: T) => void): T;
let i: { inference: string } = run((o) => {
  o.inference = "INSERT STATE HERE";
});

oThe type of is{ inference: string }it is determined to be. Because

  1. The initialization child of the declaration is the type of the declaration.{ inference: string }By
    Contextual types are attached
  2. Because the type of the return value of the call uses a contextual type for inference,
    The compiler isT={ inference: string }and infer
  3. Arrow functions use contextual types to type parameters.
    The compiler iso: { inference: string }Give

And also because this process is done while you are typing
oin addition to properties like each other in the actual program.
inferenceYou get a property completion.
Overall, thanks to this feature, TypeScript inference is like an inference engine that unifies types.
It may seem a bit, but it's not.

Type alias

The type alias istypeIt's just an alias like that.
The compiler will try to use the alias name used in the source code.
It doesn't always succeed.

type Size = [number, number];
let x: Size = [101.1, 999.9];

newtypeWhat is the closest thing to Tagged Intersection Is:

type FString = string & { __compileTimeOnly: any };

FStringdoesn't really exist__compileTimeOnlyThat
Except the compiler thinks it has a name property.
Normal string. What you meanFStringIs notstringTo
You can assign it, but you can't do the opposite.

Discrable Union

dataThe closest one is a Union type with discring formula properties.
TypeScript is usually called a discrable Union.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };

Different from Haskell, tags, or discring expressions, are
It's just a property. Each type is a unique Unit type
It has the same properties. The above is a normal Union type.
The first|is optional in the Union type syntax. Normal JavaScript code
You can use it to determine the members of Union

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };

function area(s: Shape) {
  if (s.kind === "circle") {
    return Math.PI * s.radius * s.radius;
  } else if (s.kind === "square") {
    return s.x * s.x;
  } else {
    return (s.x * s.y) / 2;
  }
}

TypeScript knows that functions are totals.areaWhat is the return type of
numberNote that it is inferred to be. If any members are not processed,
Instead ofareaWhat is the return type ofnumber | undefinedIt will be.

Also, like Haskell, common properties are visible on any Union.
Therefore, you can use common properties effectively to determine multiple members of Union.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };
// ---cut---
function height(s: Shape) {
  if (s.kind === "circle") {
    return 2 * s.radius;
  } else {
    // s.kind: "square" | "triangle"
    return s.x;
  }
}

Type parameters

Like most C languages, TypeScript declares type parameters.
Need:

function liftArray<T>(t: T): Array<T> {
  return [t];
}

It does not have to be uppercase, but type parameters are customary.
Represented by one uppercase letter. Also, type parameters are like constraints in a type class.
You can also give a type a constraint to behave on.

function firstish<T extends { length: number }>(t1: T, t2: T): T {
  return t1.length > t2.length ? t1 : t2;
}

TypeScript usually infers type arguments from a call based on the type of argument.
type arguments are usually not required.

Because TypeScript is a structural type, the nominal system
You don't need it. Specifically, the polymorphic of the function
You don't need it to create it. Type parameters are
To propagate type information, such as constraining it to be of the same type
Should be used.

function length<T extends ArrayLike<unknown>>(t: T): number {}

function length(t: ArrayLike<unknown>): number {}

FirstlengthSo you don't need t. Only once.
because it is not referenced, it is constrained by return values and other parameters.
Note that it is not used.

High floor type

TypeScript doesn't have a higher-floor type, so the following is incorrect:

function length<T extends ArrayLike<unknown>, U>(m: T<U>) {}

Point-free programming

Point-free programming — Many uses of currying and function synthesis — Is,
It's also possible in JavaScript, but it can be redundant. In TypeScript,
Because type inference for point-free programs often fails, the value parameters
Instead, you specify type parameters. As a result
It is very verbose, so it is usually better to avoid point freestyle
It would be good.

Module system

JavaScript's modern module syntax isimportAndexportFiles with
It's a bit like Haskell, except that it implicitly becomes a module.

import { value, Type } from "npm-package";
import { other, Types } from "./local-package";
import * as prefix from "../lib/third-package";

You can also import commonjs .js (modules written in nodes)
I can:

import f = require("single-function-package");

Do you want to use the export list:

export { f };

function f() {
  return g();
}
function g() {} // gはエクスポートされません

Alternatively, you can export them individually and export them:

export function f { return g() }
function g() { }

The latter style is more common, but both are in the same file.
It's possible.

readonlyAndconst

In JavaScript, the value is mutable by default.
constWhen you declare a variable using Reference will be imutable.
The referrer is still mutable:

const a = [1, 2, 3];
a.push(102); // ):
a[0] = 101; // D:

TypeScript, in addition to this, use it for propertiesreadonlyIt has qualifiers.

interface Rx {
  readonly x: number;
}
let rx: Rx = { x: 1 };
rx.x = 12; // エラー

In addition, all propertiesreadonlyThe Mapped Type toReadonly<T>Also
Introduced:

interface X {
  x: number;
}
let rx: Readonly<X> = { x: 1 };
rx.x = 12; // error

In addition, it eliminates methods with side effects and
Special prohibiting writingReadonlyArray<T>Type and,
There is a special syntax for this type.

let a: ReadonlyArray<number> = [1, 2, 3];
let b: readonly number[] = [1, 2, 3];
a.push(102); // error
b[0] = 101; // error

Assertions using const for arrays and object literals
You can also use:

let a = [1, 2, 3] as const;
a.push(102); // error
a[0] = 101; // error

However, none of these choices are defaults, and for that reason
It is not always used in TypeScript code.

Next steps

This document provides an advanced overview of the syntax and types you'll use in everyday code. Let's move on from here.

Translation of TS for JS Programmers.md

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

oneline: Learn how TypeScript extends JavaScript

TypeScript has a strange relationship with JavaScript. TypeScript provides all the functionality of JavaScript, and on top of that, it adds a layer called typescript type systems.

JavaScript, for example,stringAndnumberobjectbut does not verify that they are being admissed without conflict. However, TypeScript validates.

This means that the existing working JavaScript code is also TypeScript code. The main advantage of TypeScript is that it highlights unexpected behavior in your code and reduces the chance of bugs.

This tutorial focuses on typescript type systems and provides a brief overview of TypeScript.

Types by inference

TypeScript understands the JavaScript language and generates types in many cases.
For example, if you create a variable and assign it to a specific value, TypeScript uses that value as a type.

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

By understanding how JavaScript works, TypeScript can build a type system that accepts JavaScript code but has types. This allows you to provide a type system that does not add extra characters to specify the type in your code. In this way, in the example above, TypeScripthelloWorldButstringRecognize that it is.

You may have written JavaScript in Visual Studio Code and used editor autocomplete. Visual Studio Code uses TypeScript internally to make it easier to work with JavaScript.

Defining types

There are a wide variety of design patterns available in JavaScript. However, there are also design patterns that make it difficult to automatically infer types (for example, patterns that use dynamic programming). To cover these cases, TypeScript supports javascript language extensions, giving TypeScript space to tell you what the type is.

For instancename: stringAndid: numberTo create an object with an inferred type, including :

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

The shape of this object isinterfaceYou can explicitly write it using a declaration:

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

After variable declaration: TypeNameJavaScript objects are new by using syntax such asinterfacecan be declared to fit the shape of the

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

If you create an object that does not match the interface you define, TypeScript will warn you:

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

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

JavaScript supports class and object-oriented programming, so does TypeScript. Therefore, you can use interface declarations using 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 parameters and function return values:

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

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

booleanbigintnullnumberstringsymbolobjectAndundefinedThere are only a few primitive types available in JavaScript that can be used within the interface. TypeScript extends these a bit. For instanceany(allow anything) orunknown(Have the person who uses this type declare what the type is).)never (this type is not likely to occur), andvoid (undefinedor functions that do not have a return value).

The syntax for building types isInterfaces and type aliasesThere are two types of : The basics areinterfaceif you need a specific feature,typeIt is a good idea to use .

Type combinations

TypeScript allows you to combine simple types to create complex types. There are two common methods: using Union and using generics.

Unions

Union allows you to declare a type to be one of many. For instancebooleanTypetrueThere isfalseIt can be described as being either:

type MyBool = true | false;

Note: AboveMyBoolHover over thebooleanYou can see that it is classified into. This is a characteristic of structural systems. We're going to talk about this later.

Union type allows a certain valuestringAndnumberOfLiteralis often used to describe a set of

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

Union also allows you to work with different types. For instancearrayOrstringThere may be a function that receives:

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

To know the type of a variabletypeofUse:

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 return a value that varies depending on whether you pass a string or array to a function.

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

Generics

Generics provides variables for types. Arrays are commonly used. Sequences without generics can contain any value. An array using generics can describe the values that the array can contain.

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

You can declare your own types that use generics:

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

// 次の行はTypeScriptに`backpack`という定数があることを伝え、
// それがどこで定義されているのかを気にしないように伝える省略表現です。
declare const backpack: Backpack<string>;

// 上記でBackpackの変数部分として文字列を宣言したため、objectは文字列です。
const object = backpack.get();

// 変数部分は文字列なので、add関数に数値を渡すことはできません。
backpack.add(23);

Structural type system

One of the core principles of TypeScript is that type checking is Shape is to focus on. This is often referred to as "duck typing" or "structural typing".

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

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);

pointThe variable isPointIt has not been declared as a type. However, TypeScript is used in type checking.pointShape andPointCompare the shapes of . Because the two are of the same shape, the code passes a type check.

Even if the partial set of fields of an object matches, the shape is considered to be a 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); // "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 in how classes and objects match the shape:

// @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); // "13, 56"と出力されます

If an object or class has all the required properties, TypeScript considers them to match, regardless of the implementation details.

Next steps

This is a brief overview of the syntax and tools commonly used in TypeScript. From here you can proceed to the following steps:

Translation of TS for OOPers.md

title: TypeScript for Java/C# programmers
short: TS for Java/C# programmers
layout: docs
permalink: /ja/docs/handbook/typescript-in-5-minutes-oop.html

oneline: Learn TypeScript from the background of an object-oriented language

TypeScript is a popular choice for programmers accustomed to other statically typed languages such as C# and Java.

TypeScript type systems offer many benefits, such as improved code complementability, early detection of errors, and clarification of communication between parts of the program.
TypeScript offers many familiar features for C# and Java developers, but it's worth taking a step back and see how JavaScript (and hence TypeScript) differs from traditional object-oriented programming languages.
Understanding these differences will help you write better JavaScript code and avoid the pitfalls that programmers who go straight from C#/Java to TypeScript tend to fall into.

Inter-learning with JavaScript

If you're already familiar with JavaScript, but you're originally a Java or C# programmer, this introductory page will help you understand common misconceptions and pitfalls that are common.
Some of the ways TypeScript models types are completely different from Java and C#, and it's important to keep that in mind when learning TypeScript.

If you are a Java or C# programmer and are generally unfamiliar with JavaScript, Missing It's a good first thing to learn JavaScript a little bit.
TypeScript is a code Work Because you don't change , you still need to learn how JavaScript works in order to write code that actually does something!

TypeScript is the same as JavaScript Runtime It is important to remember that any way to achieve a particular run-time behavior (converting strings to numbers, displaying alerts, writing files to disk, etc.) always applies equally to TypeScript programs.
Don't limit your thinking to TypeScript-specific methods!

Rethinking classes

C# and Java are_Forced object-oriented programming_ It's called language.
In these languages, Class is the basic unit of code organization, and all data And It is also a basic container for runtime behavior.
Forcing all features and data to be kept in a class can be a good domain model for solving problems, but all domains are represented in this way. Need There is no.

Free functions and data

In JavaScript, functions can exist anywhere, and data is predefined.classAndstructyou can pass freely without getting inside.
This flexibility is very powerful.
Because "free" functions (functions not associated with classes) work on data that does not have a hierarchical structure of implicit object-oriented programming, it is in many cases the preferred model when writing programs in JavaScript.

Static class

In addition, C# and Java structures such as singletons and static classes are not required in TypeScript.

Object-oriented programming in TypeScript

That said, you can also use classes.
Some problems are good for solving in traditional object-oriented programming hierarchies, and support for TypeScript JavaScript classes makes these models even more powerful.
TypeScript supports many common patterns, such as interface implementations and static methods.

Classes will be discussed later in this guide.

Rethinking types

In TypeScript Type The understanding of is actually very different from that of C# and Java.
Let's explore some differences.

Nominally materialized system

In C# and Java, a given value or objectnullHas a strict type of , primitive, or known class type.
value.GetType()Andvalue.getClass()you can call a method such as , and then ask for its exact type at runtime.
The definition of this type exists somewhere in the class with a name, and you cannot substitute two classes for each other, even if they have a similar shape, unless you have an explicit inheritance relationship or a commonly implemented interface.

This is Materialization, name purpose represents the characteristics of a type system.
The types you write in your code exist at runtime, and the types are associated through declarations, not structures.

Type as a feature

In C# and Java, it makes sense to think of a one-to-one correspondence between runtime types and compile-time declarations.

In TypeScript, types have something in common. A collection of values It would be better to think as.
Because a type is just a feature, a particular value is Many can belong to a set.

As you come to think of types as aggregates, certain operations become very naturally acceptable.
For example, in C#,stringAndintout of Either it is unnatural to pass a value that is. This is because there is no single type that represents this type of value.

In TypeScript, this is very natural when you understand that all types are just aggregates.
And nowstringa set of ornumberHow should I describe a set of values belonging to either?
This value is simply a set of two Union (string | number) belongs to .

TypeScript provides many mechanisms for handling types in a set-theoretical way, and if you think of them as a set, you'll be able to use them intuitively.

Structural types to be removed

In TypeScript, objects can be of a single strict type. It isn't
For example, if you build an object that satisfies an interface, you can use the object where the interface is expected, even if there is no declarative relationship between the two.

interface Pointlike {
  x: number;
  y: number;
}
interface Named {
  name: string;
}

function logPoint(point: Pointlike) {
  console.log("x = " + point.x + ", y = " + point.y);
}

function logName(x: Named) {
  console.log("Hello, " + x.name);
}

const obj = {
  x: 0,
  y: 0,
  name: "Origin",
};

logPoint(obj);
logName(obj);

TypeScript type system Structural and not for a first-name purpose. What you meanobjIs notxAndybecause they have properties and both are numbers.PointlikeCan be used as.
The relationship between types is determined not by whether they were declared in a particular relationship, but by the properties contained in those types.

TypeScript type systems are_Materialistic_ It is not. At run timeobjButPointlikeThere is nothing to tell us that.
As a matter of factPointlikeWhen the type is run-time, In any form It does not exist.

Type as a set Going back to the idea thatobjIs notPointlikeA set of values andNamedcan be thought of as a component of both sets of values.

Structural typeing results

Object-oriented programmers are often surprised by two unique aspects of structural molding.

Empty type

The first is Empty type seems to be contrary to expectations:

class Empty {}

function fn(arg: Empty) {
  // 何かを行う
}

// エラーが出ませんが、これは'Empty'ではないのでは?
fn({ k: 10 });

TypeScript has a given argument validEmptyhere by checking iffnDetermines whether the <a0> call is valid.</a0>
This is{ k: 10 }Andclass Empty { }Of Structure You can tell by examining.
Emptyhas no properties.{ k: 10 }Is notEmptythe properties that have All you can think of it as having.
Therefore, this is a valid call!

This may seem surprising, but it is very similar to what is ultimately enforced in a nominal object-oriented programming language.
The partial type is the property of the base class. Delete You can't. This breaks the natural relationship that derived classes are part types of base classes.
Structural type systems implicitly confirm this relationship by describing partial types in terms of having compatible type properties.

Matching types

Another common cause of surprise is the matching of types:

class Car {
  drive() {
    // 車を飛ばす
  }
}
class Golfer {
  drive() {
    // ボールを遠くまで飛ばす
  }
}

// エラーにならない?
let w: Car = new Golfer();

Again, these classes Structure is the same, so there is no error.
You might think it's going to be confusing, but it's not common for classes that shouldn't actually be relevant to match.

You'll learn more about how classes are related to each other in the class chapter.

Reflection

Object-oriented programmers are familiar with the fact that even generics can ask for any type of value.

// C#
static void LogType<T>() {
    Console.WriteLine(typeof(T).Name);
}

Because typescript types are completely erased, information such as instantiation of generic type parameters is not available at run time.

JavaScript includestypeofAndinstanceofNote that these operators deal with values that exist in the output code where the type has been removed, already have limited primitives such as :
For instancetypeof (new Car())Is,"object"And then,CarAnd"Car"It does not become.


This guide is an overview. From hereHandbookAndBackground examplePlease try to go to .

Translation of TS for the New Programmer.md

title: TypeScript for novice programmers
short: TS for novice programmers
layout: docs
permalink: /ja/docs/handbook/typescript-from-scratch.html

oneline: Learn TypeScript from scratch

Congratulations on choosing TypeScript as one of your first languages -- you made a good choice!

You've probably already heard that TypeScript is JavaScript "wind" or "variant".
The relationship between TypeScript(TS) and JavaScript (JS) is so unique in modern programming languages that learning these relationships can help you understand how TypeScript made JavaScript more powerful.

What is JavaScript? Concise history

JavaScript (aka ECMAScript) was born as a simple scripting language for browsers.
When the language was invented, it was expected to be used as a snippet of short code embedded in a Web page - it would have been some of a rarer time to write more than a few dozen line of code.
As a result, early Web browsers were very slow to execute such code.
Over time, however, JS is becoming more and more popular, and Web developers are increasingly using it to create interactive experiences.

Web browser developers have responded to the increase in JS usage by optimizing the execution engine (dynamic compilation) and extending what JS can do (adding APIs), which has allowed Web developers to use JS even more.
On modern Web sites, browsers frequently run applications of hundreds of thousands of line of code.
This starts as a simple network of static pages, with all kinds of rich Application it is a long and gradual growth process of the "Web" that evolves into a platform for

More than that, JS has become popular outside the context of the browser, such as implementing JS servers using node.js.
The "can run anywhere" nature of JS is an attractive choice for class platform development.
Today, javascript to program the entire stack Only There are many developers who use .

In summary, there is a language designed for quick use, which has grown as a full-fledged tool for writing millions of line of applications.
In any language, you can Habit (specificity and surprise), but javascript has its humble beginnings, especially A lot I have a habit. Let's look at some examples:

  • JavaScript equivalence operators (==) is the argument Type coercion but this causes unexpected behavior:

    if ("" == 0) {
      // これは等価です! でもなぜ??
    }
    if (1 < x < 3) {
      // x が "どのような" 値であっても True です!
    }
  • JavaScript also allows you to access properties that do not exist:

    const obj = { width: 10, height: 15 };
    // なぜこれが NaN なのか?正しくスペルを打つのが難しい!
    const area = obj.width * obj.heigth;

Most programming languages throw errors when these errors occur. Some languages throw errors during compilation, that is, before executing code.
These habits are annoying when you're writing a small program, but you can manage it. On the other hand, when you're writing an application with hundreds or thousands of line of code, these quirks come up one after another and become a serious problem.

TypeScript: Static Type Checker

We mentioned earlier that some languages can't run these buggy programs.
Detecting errors without running code Static check It is said.
Detecting what is an error and what is not an error, based on the type of value being manipulated, is a static Type It's called a check.

TypeScript checks the program for errors before executing. Value type because it's done on the basis of Static type checker It can be said.
For example, in the last example above,objOf Type is causing an error.
Here are the errors typescript detected:

// @errors: 2551
const obj = { width: 10, height: 15 };
const area = obj.width * obj.heigth;

JavaScript Typed Superset

By the way, what does TypeScript have to do with JavaScript?

Syntax

TypeScript is a JavaScript Super Set The language in which it is. Therefore, the JS syntax is the correct TS.
Syntax is how you write the text that forms a program.
For example, the following code:)Because there is no Syntax An error occurs.

// @errors: 1005
let a = (4

TypeScript does not believe that any JavaScript code will cause errors due to syntax.
This means that you don't have to care about how JavaScript is written, and you can put any running JavaScript code in a TypeScript file.

Type

However, TypeScript Typed It is a super set. In other words, it is a language that add rules such as how different types of values can be used.
The aforementionedobj.heigthThe error in Syntax is not an error. Some values (Type) in the wrong way.

Another example is JavaScript code that can be run in a browser and will log values.

console.log(4 / []);

This is a syntactically correct program.Infinityand output.
However, TypeScript considers the division of numbers by array to be a non-meaningful operation and will cause an error.

// @errors: 2363
console.log(4 / []);

It's possible that you tried to split a number in an array just to see what would happen, but most of the time it would be a programming mistake.
TypeScript type checkers are designed to allow the correct program to pass through and catch common errors as much as possible at the same time.
(Later, you're going to learn about settings that adjust the degree to which TypeScript checks your code.) )

If you move code from a JavaScript file to a TypeScript file, depending on how you write the code, Type error may appear.
These may be problems that make sense in your code, or they may be that TypeScript is becoming overly conservative.
This guide explains how to add various TypeScript syntaxes to eliminate these errors.

Running behavior

TypeScript is a JavaScript Running behavior it is also a programming language that maintains
For example, in JavaScript, division by 0 does not cause a run-time exception.Infinityis generated.
As a general rule, TypeScript uses javascript code to run Never Do not change.

This means that if you migrate code from JavaScript to TypeScript, typescript will do the same even if it detects a type error in your code. Guarantee It has been.

Maintaining the same runtime behavior as JavaScript is a fundamental promise of TypeScript. This means that you can easily migrate between the two languages without worrying about the small differences that can cause the program to stop working.

Delete type

Roughly speaking, once the TypeScript compiler has finished checking the code, it will Delete I will.
This means that once the code is compiled, the resulting JS code does not contain type information.

This is also based on the type inferred by TypeScript. Work will never change.
In short, you may see a type error during compilation, but the type system itself has nothing to do with the running behavior of the program.

And finally, TypeScript does not add runtime libraries.
Your program uses the same standard (or external) libraries as JavaScript programs, so you don't add TypeScript-specific frameworks that need to be learned.

Learning JavaScript and TypeScript

"Which should I learn, JavaScript or TypeScript?" "I often see the question.

The answer is, you can't learn TypeScript without learning It!
Because TypeScript shares JavaScript with syntax and running behavior, learning JavaScript can also lead to learning TypeScript.

There is a lot of material for programmers to learn JavaScript. If you're writing TypeScript, you can't ignore these articles.
For example, StackOverflowjavascriptThe question tagged withtypescriptabout 20 times, butjavascriptThe question is All This also apply to TypeScript.

If you notice that you are searching for something like "How to sort lists in TypeScript",TypeScript is a JavaScript runtime with a compile-time type checker Remember that.
Sorting lists in TypeScript is the same as in JavaScript.
If you find material that uses TypeScript directly, that's great, but don't limit your thinking to common questions about how to accomplish runtime tasks when you need TypeScript-specific answers.


Now it's a good time to learn the basics of JavaScript. (Mozilla Web Docs JavaScript Guideis a good starting point. )

Once you get used to it,TypeScript for JavaScript ProgrammersAnd thenHandbookOrBackground exampleTry reading .

Generated by 🚫 dangerJS against 41d811b

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