-
Notifications
You must be signed in to change notification settings - Fork 130
[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
base: main
Are you sure you want to change the base?
Conversation
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. |
Translation of TS for Functional Programmers.mdtitle: TypeScript for functional programmers oneline: Learn TypeScript from a functional programming backgroundTypeScript allows Microsoft programmers to use traditional object-oriented programs on the Web This primer is an active student who wants to learn TypeScript. Object-oriented programming is not discussed here. PremiseThis primer assumes that you know:
If you need to learn about the benefits of JavaScript, The C++ Programming LanguageIs not Concepts not d't dinged in HaskellBuilt-in typesJavaScript defines eight built-in types:
For details, please refer to the MDN page.. TypeScript has primitive types that correspond to built-in types:
Other important TypeScript types
Note:
Boxed typesJavaScript has boxed types that are equivalent to primitive types. (1).toExponential();
// 上記は次と等しい
Number.prototype.toExponential.call(1); When calling a method of numerical literals, to make the parser understand ProgressiveTypeScript is always used whenever you don't know the type of an expression. // tsconfig.jsonで"noImplicitAny": falseの場合は、anys: any[]とします
const anys = [];
anys.push(1);
anys.push("oh no");
anys.push({ anything: "goes" }); And anys.map(anys[1]); // oh no, "oh no"は関数ではありません Also let sepsis = anys[0] + anys[1]; // どんな値でも入れることができます TypeScript StructuralStructural typeing is familiar to most functional programmers. // @strict: false
let o = { x: "hi", extra: 1 }; // ok
let o2: { x: string } = o; // ok Here, the object literal Named types simply name the type. For assignment purposes // @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(); UnionsIn TypeScript, the Union type is not tagged. In other words, 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;
}
}
The following types have built-in ad fore languages:
Functions and arrays are objects at run time, but they have their own ad noted IntersectionsIn addition to Union, TypeScript also has intersections: type Combined = { a: number } & { b: string };
type Conflicting = { a: number } & { a: string };
Unit typeThe Unit type is a primitive type partial type that has a strict single primitive value. declare function pad(s: string, n: number, direction: "left" | "right"): string;
pad("hi", 10, "left"); If necessary, the compiler may, for example, // @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:
declare function pad(s: string, n: number, direction: "left" | "right"): string;
// ---cut---
let s: "left" | "right" = "right";
pad("hi", 10, s); Haskell-like conceptContextual typeTypeScript reveals variable declarations, and so on. let s = "I'm a string!"; However, for those who have used other C syntax languages, declare function map<T, U>(f: (t: T) => U, ts: T[]): U[];
let sns = map((n) => n.toString(), [1, 2, 3]); Above, before the call Inference works in any order, but intellisense declare function map<T, U>(ts: T[], f: (t: T) => U): U[]; Contextual types are object literals and otherwise declare function run<T>(thunk: (t: T) => void): T;
let i: { inference: string } = run((o) => {
o.inference = "INSERT STATE HERE";
});
And also because this process is done while you are typing Type aliasThe type alias is type Size = [number, number];
let x: Size = [101.1, 999.9];
type FString = string & { __compileTimeOnly: any };
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 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. Also, like Haskell, common properties are visible on any 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 parametersLike most C languages, TypeScript declares type parameters. function liftArray<T>(t: T): Array<T> {
return [t];
} It does not have to be uppercase, but type parameters are customary. 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. Because TypeScript is a structural type, the nominal system function length<T extends ArrayLike<unknown>>(t: T): number {}
function length(t: ArrayLike<unknown>): number {} First High floor typeTypeScript doesn't have a higher-floor type, so the following is incorrect: function length<T extends ArrayLike<unknown>, U>(m: T<U>) {} Point-free programmingPoint-free programming — Many uses of currying and function synthesis — Is, Module systemJavaScript's modern module syntax is 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) 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.
|
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);
point
The variable isPoint
It has not been declared as a type. However, TypeScript is used in type checking.point
Shape andPoint
Compare 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:
- I need a handbook.From start to finishRead (30 minutes)
- Background exampleExplore
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.class
Andstruct
you 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 objectnull
Has 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#,string
Andint
out 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 nowstring
a set of ornumber
How 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 meanobj
Is notx
Andy
because they have properties and both are numbers.Pointlike
Can 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 timeobj
ButPointlike
There is nothing to tell us that.
As a matter of factPointlike
When the type is run-time, In any form It does not exist.
Type as a set Going back to the idea thatobj
Is notPointlike
A set of values andNamed
can 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 validEmpty
here by checking iffn
Determines whether the <a0> call is valid.</a0>
This is{ k: 10 }
Andclass Empty { }
Of Structure You can tell by examining.
Empty
has no properties.{ k: 10 }
Is notEmpty
the 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 includestypeof
Andinstanceof
Note 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,Car
And"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,obj
Of 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.heigth
The 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.Infinity
and 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.Infinity
is 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, StackOverflowjavascript
The question tagged withtypescript
about 20 times, butjavascript
The 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 .
ref: #3
diff: 41d811b