From 2d1ce6deb63f6e0b7f506a5f2d60acbdcbac8758 Mon Sep 17 00:00:00 2001 From: Masato Urai Date: Mon, 15 Feb 2021 00:04:46 +0900 Subject: [PATCH 1/2] copy original files --- .../TS for Functional Programmers.md | 597 ++++++++++++++++++ .../ja/get-started/TS for JS Programmers.md | 290 +++++++++ .../ja/get-started/TS for OOPers.md | 191 ++++++ .../get-started/TS for the New Programmer.md | 187 ++++++ 4 files changed, 1265 insertions(+) create mode 100644 docs/documentation/ja/get-started/TS for Functional Programmers.md create mode 100644 docs/documentation/ja/get-started/TS for JS Programmers.md create mode 100644 docs/documentation/ja/get-started/TS for OOPers.md create mode 100644 docs/documentation/ja/get-started/TS for the New Programmer.md diff --git a/docs/documentation/ja/get-started/TS for Functional Programmers.md b/docs/documentation/ja/get-started/TS for Functional Programmers.md new file mode 100644 index 00000000..60945cd9 --- /dev/null +++ b/docs/documentation/ja/get-started/TS for Functional Programmers.md @@ -0,0 +1,597 @@ +--- +title: TypeScript for Functional Programmers +short: TS for Functional Programmers +layout: docs +permalink: /docs/handbook/typescript-in-5-minutes-func.html +oneline: Learn TypeScript if you have a background in functional programming +--- + +TypeScript began its life as an attempt to bring traditional object-oriented types +to JavaScript so that the programmers at Microsoft could bring +traditional object-oriented programs to the web. As it has developed, TypeScript's type +system has evolved to model code written by native JavaScripters. The +resulting system is powerful, interesting and messy. + +This introduction is designed for working Haskell or ML programmers +who want to learn TypeScript. It describes how the type system of +TypeScript differs from Haskell's type system. It also describes +unique features of TypeScript's type system that arise from its +modelling of JavaScript code. + +This introduction does not cover object-oriented programming. In +practice, object-oriented programs in TypeScript are similar to those +in other popular languages with OO features. + +## Prerequisites + +In this introduction, I assume you know the following: + +- How to program in JavaScript, the good parts. +- Type syntax of a C-descended language. + +If you need to learn the good parts of JavaScript, read +[JavaScript: The Good Parts](http://shop.oreilly.com/product/9780596517748.do). +You may be able to skip the book if you know how to write programs in +a call-by-value lexically scoped language with lots of mutability and +not much else. +[R4RS Scheme](https://people.csail.mit.edu/jaffer/r4rs.pdf) is a good example. + +[The C++ Programming Language](http://www.stroustrup.com/4th.html) is +a good place to learn about C-style type syntax. Unlike C++, +TypeScript uses postfix types, like so: `x: string` instead of `string x`. + +## Concepts not in Haskell + +## Built-in types + +JavaScript defines 8 built-in types: + +| Type | Explanation | +| ----------- | ------------------------------------------- | +| `Number` | a double-precision IEEE 754 floating point. | +| `String` | an immutable UTF-16 string. | +| `BigInt` | integers in the arbitrary precision format. | +| `Boolean` | `true` and `false`. | +| `Symbol` | a unique value usually used as a key. | +| `Null` | equivalent to the unit type. | +| `Undefined` | also equivalent to the unit type. | +| `Object` | similar to records. | + +[See the MDN page for more detail](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures). + +TypeScript has corresponding primitive types for the built-in types: + +- `number` +- `string` +- `bigint` +- `boolean` +- `symbol` +- `null` +- `undefined` +- `object` + +### Other important TypeScript types + +| Type | Explanation | +| -------------- | ----------------------------------------------------------- | +| `unknown` | the top type. | +| `never` | the bottom type. | +| object literal | eg `{ property: Type }` | +| `void` | a subtype of `undefined` intended for use as a return type. | +| `T[]` | mutable arrays, also written `Array` | +| `[T, T]` | tuples, which are fixed-length but mutable | +| `(t: T) => U` | functions | + +Notes: + +1. Function syntax includes parameter names. This is pretty hard to get used to! + + ```ts + let fst: (a: any, b: any) => any = (a, b) => a; + + // or more precisely: + + let fst: (a: T, b: U) => T = (a, b) => a; + ``` + +2. Object literal type syntax closely mirrors object literal value syntax: + + ```ts + let o: { n: number; xs: object[] } = { n: 1, xs: [] }; + ``` + +3. `[T, T]` is a subtype of `T[]`. This is different than Haskell, where tuples are not related to lists. + +### Boxed types + +JavaScript has boxed equivalents of primitive types that contain the +methods that programmers associate with those types. TypeScript +reflects this with, for example, the difference between the primitive +type `number` and the boxed type `Number`. The boxed types are rarely +needed, since their methods return primitives. + +```ts +(1).toExponential(); +// equivalent to +Number.prototype.toExponential.call(1); +``` + +Note that calling a method on a numeric literal requires it to be in +parentheses to aid the parser. + +## Gradual typing + +TypeScript uses the type `any` whenever it can't tell what the type of +an expression should be. Compared to `Dynamic`, calling `any` a type +is an overstatement. It just turns off the type checker +wherever it appears. For example, you can push any value into an +`any[]` without marking the value in any way: + +```ts twoslash +// with "noImplicitAny": false in tsconfig.json, anys: any[] +const anys = []; +anys.push(1); +anys.push("oh no"); +anys.push({ anything: "goes" }); +``` + +And you can use an expression of type `any` anywhere: + +```ts +anys.map(anys[1]); // oh no, "oh no" is not a function +``` + +`any` is contagious, too — if you initialise a variable with an +expression of type `any`, the variable has type `any` too. + +```ts +let sepsis = anys[0] + anys[1]; // this could mean anything +``` + +To get an error when TypeScript produces an `any`, use +`"noImplicitAny": true`, or `"strict": true` in `tsconfig.json`. + +## Structural typing + +Structural typing is a familiar concept to most functional +programmers, although Haskell and most MLs are not +structurally typed. Its basic form is pretty simple: + +```ts +// @strict: false +let o = { x: "hi", extra: 1 }; // ok +let o2: { x: string } = o; // ok +``` + +Here, the object literal `{ x: "hi", extra: 1 }` has a matching +literal type `{ x: string, extra: number }`. That +type is assignable to `{ x: string }` since +it has all the required properties and those properties have +assignable types. The extra property doesn't prevent assignment, it +just makes it a subtype of `{ x: string }`. + +Named types just give a name to a type; for assignability purposes +there's no difference between the type alias `One` and the interface +type `Two` below. They both have a property `p: string`. (Type aliases +behave differently from interfaces with respect to recursive +definitions and type parameters, however.) + +```ts twoslash +// @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, union types are untagged. In other words, they are not +discriminated unions like `data` in Haskell. However, you can often +discriminate types in a union using built-in tags or other properties. + +```ts twoslash +function start( + arg: string | string[] | (() => string) | { s: string } +): string { + // this is super common in 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 { + // finally, just convert a string to another string + return s; + } +} +``` + +`string`, `Array` and `Function` have built-in type predicates, +conveniently leaving the object type for the `else` branch. It is +possible, however, to generate unions that are difficult to +differentiate at runtime. For new code, it's best to build only +discriminated unions. + +The following types have built-in predicates: + +| 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"` | + +Note that functions and arrays are objects at runtime, but have their +own predicates. + +### Intersections + +In addition to unions, TypeScript also has intersections: + +```ts twoslash +type Combined = { a: number } & { b: string }; +type Conflicting = { a: number } & { a: string }; +``` + +`Combined` has two properties, `a` and `b`, just as if they had been +written as one object literal type. Intersection and union are +recursive in case of conflicts, so `Conflicting.a: number & string`. + +## Unit types + +Unit types are subtypes of primitive types that contain exactly one +primitive value. For example, the string `"foo"` has the type +`"foo"`. Since JavaScript has no built-in enums, it is common to use a set of +well-known strings instead. Unions of string literal types allow +TypeScript to type this pattern: + +```ts twoslash +declare function pad(s: string, n: number, direction: "left" | "right"): string; +pad("hi", 10, "left"); +``` + +When needed, the compiler _widens_ — converts to a +supertype — the unit type to the primitive type, such as `"foo"` +to `string`. This happens when using mutability, which can hamper some +uses of mutable variables: + +```ts twoslash +// @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"' +``` + +Here's how the error happens: + +- `"right": "right"` +- `s: string` because `"right"` widens to `string` on assignment to a mutable variable. +- `string` is not assignable to `"left" | "right"` + +You can work around this with a type annotation for `s`, but that +in turn prevents assignments to `s` of variables that are not of type +`"left" | "right"`. + +```ts twoslash +declare function pad(s: string, n: number, direction: "left" | "right"): string; +// ---cut--- +let s: "left" | "right" = "right"; +pad("hi", 10, s); +``` + +## Concepts similar to Haskell + +## Contextual typing + +TypeScript has some obvious places where it can infer types, like +variable declarations: + +```ts twoslash +let s = "I'm a string!"; +``` + +But it also infers types in a few other places that you may not expect +if you've worked with other C-syntax languages: + +```ts twoslash +declare function map(f: (t: T) => U, ts: T[]): U[]; +let sns = map((n) => n.toString(), [1, 2, 3]); +``` + +Here, `n: number` in this example also, despite the fact that `T` and `U` +have not been inferred before the call. In fact, after `[1,2,3]` has +been used to infer `T=number`, the return type of `n => n.toString()` +is used to infer `U=string`, causing `sns` to have the type +`string[]`. + +Note that inference will work in any order, but intellisense will only +work left-to-right, so TypeScript prefers to declare `map` with the +array first: + +```ts twoslash +declare function map(ts: T[], f: (t: T) => U): U[]; +``` + +Contextual typing also works recursively through object literals, and +on unit types that would otherwise be inferred as `string` or +`number`. And it can infer return types from context: + +```ts twoslash +declare function run(thunk: (t: T) => void): T; +let i: { inference: string } = run((o) => { + o.inference = "INSERT STATE HERE"; +}); +``` + +The type of `o` is determined to be `{ inference: string }` because + +1. Declaration initialisers are contextually typed by the + declaration's type: `{ inference: string }`. +2. The return type of a call uses the contextual type for inferences, + so the compiler infers that `T={ inference: string }`. +3. Arrow functions use the contextual type to type their parameters, + so the compiler gives `o: { inference: string }`. + +And it does so while you are typing, so that after typing `o.`, you +get completions for the property `inference`, along with any other +properties you'd have in a real program. +Altogether, this feature can make TypeScript's inference look a bit +like a unifying type inference engine, but it is not. + +## Type aliases + +Type aliases are mere aliases, just like `type` in Haskell. The +compiler will attempt to use the alias name wherever it was used in +the source code, but does not always succeed. + +```ts twoslash +type Size = [number, number]; +let x: Size = [101.1, 999.9]; +``` + +The closest equivalent to `newtype` is a _tagged intersection_: + +```ts +type FString = string & { __compileTimeOnly: any }; +``` + +An `FString` is just like a normal string, except that the compiler +thinks it has a property named `__compileTimeOnly` that doesn't +actually exist. This means that `FString` can still be assigned to +`string`, but not the other way round. + +## Discriminated Unions + +The closest equivalent to `data` is a union of types with discriminant +properties, normally called discriminated unions in TypeScript: + +```ts +type Shape = + | { kind: "circle"; radius: number } + | { kind: "square"; x: number } + | { kind: "triangle"; x: number; y: number }; +``` + +Unlike Haskell, the tag, or discriminant, is just a property in each +object type. Each variant has an identical property with a different +unit type. This is still a normal union type; the leading `|` is +an optional part of the union type syntax. You can discriminate the +members of the union using normal JavaScript code: + +```ts twoslash +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; + } +} +``` + +Note that the return type of `area` is inferred to be `number` because +TypeScript knows the function is total. If some variant is not +covered, the return type of `area` will be `number | undefined` instead. + +Also, unlike Haskell, common properties show up in any union, so you +can usefully discriminate multiple members of the union: + +```ts twoslash +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-descended languages, TypeScript requires declaration of +type parameters: + +```ts +function liftArray(t: T): Array { + return [t]; +} +``` + +There is no case requirement, but type parameters are conventionally +single uppercase letters. Type parameters can also be constrained to a +type, which behaves a bit like type class constraints: + +```ts +function firstish(t1: T, t2: T): T { + return t1.length > t2.length ? t1 : t2; +} +``` + +TypeScript can usually infer type arguments from a call based on the +type of the arguments, so type arguments are usually not needed. + +Because TypeScript is structural, it doesn't need type parameters as +much as nominal systems. Specifically, they are not needed to make a +function polymorphic. Type parameters should only be used to +_propagate_ type information, such as constraining parameters to be +the same type: + +```ts +function length>(t: T): number {} + +function length(t: ArrayLike): number {} +``` + +In the first `length`, T is not necessary; notice that it's only +referenced once, so it's not being used to constrain the type of the +return value or other parameters. + +### Higher-kinded types + +TypeScript does not have higher kinded types, so the following is not legal: + +```ts +function length, U>(m: T) {} +``` + +### Point-free programming + +Point-free programming — heavy use of currying and function +composition — is possible in JavaScript, but can be verbose. +In TypeScript, type inference often fails for point-free programs, so +you'll end up specifying type parameters instead of value parameters. The +result is so verbose that it's usually better to avoid point-free +programming. + +## Module system + +JavaScript's modern module syntax is a bit like Haskell's, except that +any file with `import` or `export` is implicitly a module: + +```ts +import { value, Type } from "npm-package"; +import { other, Types } from "./local-package"; +import * as prefix from "../lib/third-package"; +``` + +You can also import commonjs modules — modules written using node.js' +module system: + +```ts +import f = require("single-function-package"); +``` + +You can export with an export list: + +```ts +export { f }; + +function f() { + return g(); +} +function g() {} // g is not exported +``` + +Or by marking each export individually: + +```ts +export function f { return g() } +function g() { } +``` + +The latter style is more common but both are allowed, even in the same +file. + +## `readonly` and `const` + +In JavaScript, mutability is the default, although it allows variable +declarations with `const` to declare that the _reference_ is +immutable. The referent is still mutable: + +```js +const a = [1, 2, 3]; +a.push(102); // ): +a[0] = 101; // D: +``` + +TypeScript additionally has a `readonly` modifier for properties. + +```ts +interface Rx { + readonly x: number; +} +let rx: Rx = { x: 1 }; +rx.x = 12; // error +``` + +It also ships with a mapped type `Readonly` that makes +all properties `readonly`: + +```ts +interface X { + x: number; +} +let rx: Readonly = { x: 1 }; +rx.x = 12; // error +``` + +And it has a specific `ReadonlyArray` type that removes +side-affecting methods and prevents writing to indices of the array, +as well as special syntax for this type: + +```ts +let a: ReadonlyArray = [1, 2, 3]; +let b: readonly number[] = [1, 2, 3]; +a.push(102); // error +b[0] = 101; // error +``` + +You can also use a const-assertion, which operates on arrays and +object literals: + +```ts +let a = [1, 2, 3] as const; +a.push(102); // error +a[0] = 101; // error +``` + +However, none of these options are the default, so they are not +consistently used in TypeScript code. + +## Next Steps + +This doc is a high level overview of the syntax and types you would use in everyday code. From here you should: + +- Read the full Handbook [from start to finish](/docs/handbook/intro.html) (30m) +- Explore the [Playground examples](/play#show-examples). diff --git a/docs/documentation/ja/get-started/TS for JS Programmers.md b/docs/documentation/ja/get-started/TS for JS Programmers.md new file mode 100644 index 00000000..f35ba88f --- /dev/null +++ b/docs/documentation/ja/get-started/TS for JS Programmers.md @@ -0,0 +1,290 @@ +--- +title: TypeScript for JavaScript Programmers +short: TypeScript for JS Programmers +layout: docs +permalink: /docs/handbook/typescript-in-5-minutes.html +oneline: Learn how TypeScript extends JavaScript +--- + +TypeScript stands in an unusual relationship to JavaScript. TypeScript offers all of JavaScript's features, and an additional layer on top of these: TypeScript's type system. + +For example, JavaScript provides language primitives like `string`, `number`, and `object`, but it doesn't check that you've consistently assigned these. TypeScript does. + +This means that your existing working JavaScript code is also TypeScript code. The main benefit of TypeScript is that it can highlight unexpected behavior in your code, lowering the chance of bugs. + +This tutorial provides a brief overview of TypeScript, focusing on its type system. + +## Types by Inference + +TypeScript knows the JavaScript language and will generate types for you in many cases. +For example in creating a variable and assigning it to a particular value, TypeScript will use the value as its type. + +```ts twoslash +let helloWorld = "Hello World"; +// ^? +``` + +By understanding how JavaScript works, TypeScript can build a type-system that accepts JavaScript code but has types. This offers a type-system without needing to add extra characters to make types explicit in your code. That's how TypeScript knows that `helloWorld` is a `string` in the above example. + +You may have written JavaScript in Visual Studio Code, and had editor auto-completion. Visual Studio Code uses TypeScript under the hood to make it easier to work with JavaScript. + +## Defining Types + +You can use a wide variety of design patterns in JavaScript. However, some design patterns make it difficult for types to be inferred automatically (for example, patterns that use dynamic programming). To cover these cases, TypeScript supports an extension of the JavaScript language, which offers places for you to tell TypeScript what the types should be. + +For example, to create an object with an inferred type which includes `name: string` and `id: number`, you can write: + +```ts twoslash +const user = { + name: "Hayes", + id: 0, +}; +``` + +You can explicitly describe this object's shape using an `interface` declaration: + +```ts twoslash +interface User { + name: string; + id: number; +} +``` + +You can then declare that a JavaScript object conforms to the shape of your new `interface` by using syntax like `: TypeName` after a variable declaration: + +```ts twoslash +interface User { + name: string; + id: number; +} +// ---cut--- +const user: User = { + name: "Hayes", + id: 0, +}; +``` + +If you provide an object that doesn't match the interface you have provided, TypeScript will warn you: + +```ts twoslash +// @errors: 2322 +interface User { + name: string; + id: number; +} + +const user: User = { + username: "Hayes", + id: 0, +}; +``` + +Since JavaScript supports classes and object-oriented programming, so does TypeScript. You can use an interface declaration with classes: + +```ts twoslash +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 interfaces to annotate parameters and return values to functions: + +```ts twoslash +// @noErrors +interface User { + name: string; + id: number; +} +// ---cut--- +function getAdminUser(): User { + //... +} + +function deleteUser(user: User) { + // ... +} +``` + +There are already a small set of primitive types available in JavaScript: `boolean`, `bigint`, `null`, `number`, `string`, `symbol`, `object`, and `undefined`, which you can use in an interface. TypeScript extends this list with a few more, such as `any` (allow anything), [`unknown`](/play#example/unknown-and-never) (ensure someone using this type declares what the type is), [`never`](/play#example/unknown-and-never) (it's not possible that this type could happen), and `void` (a function which returns `undefined` or has no return value). + +You'll see that there are two syntaxes for building types: [Interfaces and Types](/play/?e=83#example/types-vs-interfaces). You should prefer `interface`. Use `type` when you need specific features. + +## Composing Types + +With TypeScript, you can create complex types by combining simple ones. There are two popular ways to do so: with Unions, and with Generics. + +### Unions + +With a union, you can declare that a type could be one of many types. For example, you can describe a `boolean` type as being either `true` or `false`: + +```ts twoslash +type MyBool = true | false; +``` + +_Note:_ If you hover over `MyBool` above, you'll see that it is classed as `boolean`. That's a property of the Structural Type System. More on this below. + +A popular use-case for union types is to describe the set of `string`s or `number`s [literal](/docs/handbook/literal-types.html) that a value is allowed to be: + +```ts twoslash +type WindowStates = "open" | "closed" | "minimized"; +type LockStates = "locked" | "unlocked"; +type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9; +``` + +Unions provide a way to handle different types too. For example, you may have a function that takes an `array` or a `string`: + +```ts twoslash +function getLength(obj: string | string[]) { + return obj.length; +} +``` + +To learn the type of a variable, use `typeof`: + +| 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 make a function return different values depending on whether it is passed a string or an array: + + +```ts twoslash +function wrapInArray(obj: string | string[]) { + if (typeof obj === "string") { + return [obj]; +// ^? + } else { + return obj; + } +} +``` + +### Generics + +Generics provide variables to types. A common example is an array. An array without generics could contain anything. An array with generics can describe the values that the array contains. + +```ts +type StringArray = Array; +type NumberArray = Array; +type ObjectWithNameArray = Array<{ name: string }>; +``` + +You can declare your own types that use generics: + +```ts twoslash +// @errors: 2345 +interface Backpack { + add: (obj: Type) => void; + get: () => Type; +} + +// This line is a shortcut to tell TypeScript there is a +// constant called `backpack`, and to not worry about where it came from. +declare const backpack: Backpack; + +// object is a string, because we declared it above as the variable part of Backpack. +const object = backpack.get(); + +// Since the backpack variable is a string, you can't pass a number to the add function. +backpack.add(23); +``` + +## Structural Type System + +One of TypeScript's core principles is that type checking focuses on the _shape_ that values have. This is sometimes called "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. + +```ts twoslash +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); +``` + +The `point` variable is never declared to be a `Point` type. However, TypeScript compares the shape of `point` to the shape of `Point` in the type-check. They have the same shape, so the code passes. + +The shape-matching only requires a subset of the object's fields to match. + +```ts twoslash +// @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 between how classes and objects conform to shapes: + +```ts twoslash +// @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 the object or class has all the required properties, TypeScript will say they match, regardless of the implementation details. + +## Next Steps + +This was a brief overview of the syntax and tools used in everyday TypeScript. From here, you can: + +- Read the full Handbook [from start to finish](/docs/handbook/intro.html) (30m) +- Explore the [Playground examples](/play#show-examples). diff --git a/docs/documentation/ja/get-started/TS for OOPers.md b/docs/documentation/ja/get-started/TS for OOPers.md new file mode 100644 index 00000000..a7ba8007 --- /dev/null +++ b/docs/documentation/ja/get-started/TS for OOPers.md @@ -0,0 +1,191 @@ +--- +title: TypeScript for Java/C# Programmers +short: TS for Java/C# Programmers +layout: docs +permalink: /docs/handbook/typescript-in-5-minutes-oop.html +oneline: Learn TypeScript if you have a background in object-oriented languages +--- + +TypeScript is a popular choice for programmers accustomed to other languages with static typing, such as C# and Java. + +TypeScript's type system offers many of the same benefits, such as better code completion, earlier detection of errors, and clearer communication between parts of your program. +While TypeScript provides many familiar features for these developers, it's worth stepping back to see how JavaScript (and therefore TypeScript) differ from traditional OOP languages. +Understanding these differences will help you write better JavaScript code, and avoid common pitfalls that programmers who go straight from C#/Java to TypeScript may fall in to. + +## Co-learning JavaScript + +If you're familiar with JavaScript already but are primarily a Java or C# programmer, this introductory page can help explain some of the common misconceptions and pitfalls you might be susceptible to. +Some of the ways that TypeScript models types are quite different from Java or C#, and it's important to keep these in mind when learning TypeScript. + +If you're a Java or C# programmer that is new to JavaScript in general, we recommend learning a little bit of JavaScript _without_ types first to understand JavaScript's runtime behaviors. +Because TypeScript doesn't change how your code _runs_, you'll still have to learn how JavaScript works in order to write code that actually does something! + +It's important to remember that TypeScript uses the same _runtime_ as JavaScript, so any resources about how to accomplish specific runtime behavior (converting a string to a number, displaying an alert, writing a file to disk, etc.) will always apply equally well to TypeScript programs. +Don't limit yourself to TypeScript-specific resources! + +## Rethinking the Class + +C# and Java are what we might call _mandatory OOP_ languages. +In these languages, the _class_ is the basic unit of code organization, and also the basic container of all data _and_ behavior at runtime. +Forcing all functionality and data to be held in classes can be a good domain model for some problems, but not every domain _needs_ to be represented this way. + +### Free Functions and Data + +In JavaScript, functions can live anywhere, and data can be passed around freely without being inside a pre-defined `class` or `struct`. +This flexibility is extremely powerful. +"Free" functions (those not associated with a class) working over data without an implied OOP hierarchy tends to be the preferred model for writing programs in JavaScript. + +### Static Classes + +Additionally, certain constructs from C# and Java such as singletons and static classes are unnecessary in TypeScript. + +## OOP in TypeScript + +That said, you can still use classes if you like! +Some problems are well-suited to being solved by a traditional OOP hierarchy, and TypeScript's support for JavaScript classes will make these models even more powerful. +TypeScript supports many common patterns such as implementing interfaces, inheritance, and static methods. + +We'll cover classes later in this guide. + +## Rethinking Types + +TypeScript's understanding of a _type_ is actually quite different from C# or Java's. +Let's explore some differences. + +### Nominal Reified Type Systems + +In C# or Java, any given value or object has one exact type - either `null`, a primitive, or a known class type. +We can call methods like `value.GetType()` or `value.getClass()` to query the exact type at runtime. +The definition of this type will reside in a class somewhere with some name, and we can't use two classes with similar shapes in lieu of each other unless there's an explicit inheritance relationship or commonly-implemented interface. + +These aspects describe a _reified, nominal_ type system. +The types we wrote in the code are present at runtime, and the types are related via their declarations, not their structures. + +### Types as Sets + +In C# or Java, it's meaningful to think of a one-to-one correspondence between runtime types and their compile-time declarations. + +In TypeScript, it's better to think of a type as a _set of values_ that share something in common. +Because types are just sets, a particular value can belong to _many_ sets at the same time. + +Once you start thinking of types as sets, certain operations become very natural. +For example, in C#, it's awkward to pass around a value that is _either_ a `string` or `int`, because there isn't a single type that represents this sort of value. + +In TypeScript, this becomes very natural once you realize that every type is just a set. +How do you describe a value that either belongs in the `string` set or the `number` set? +It simply belongs to the _union_ of those sets: `string | number`. + +TypeScript provides a number of mechanisms to work with types in a set-theoretic way, and you'll find them more intuitive if you think of types as sets. + +### Erased Structural Types + +In TypeScript, objects are _not_ of a single exact type. +For example, if we construct an object that satisfies an interface, we can use that object where that interface is expected even though there was no declarative relationship between the two. + +```ts twoslash +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's type system is _structural_, not nominal: We can use `obj` as a `Pointlike` because it has `x` and `y` properties that are both numbers. +The relationships between types are determined by the properties they contain, not whether they were declared with some particular relationship. + +TypeScript's type system is also _not reified_: There's nothing at runtime that will tell us that `obj` is `Pointlike`. +In fact, the `Pointlike` type is not present _in any form_ at runtime. + +Going back to the idea of _types as sets_, we can think of `obj` as being a member of both the `Pointlike` set of values and the `Named` set of values. + +### Consequences of Structural Typing + +OOP programmers are often surprised by two particular aspects of structural typing. + +#### Empty Types + +The first is that the _empty type_ seems to defy expectation: + +```ts twoslash +class Empty {} + +function fn(arg: Empty) { + // do something? +} + +// No error, but this isn't an 'Empty' ? +fn({ k: 10 }); +``` + +TypeScript determines if the call to `fn` here is valid by seeing if the provided argument is a valid `Empty`. +It does so by examining the _structure_ of `{ k: 10 }` and `class Empty { }`. +We can see that `{ k: 10 }` has _all_ of the properties that `Empty` does, because `Empty` has no properties. +Therefore, this is a valid call! + +This may seem surprising, but it's ultimately a very similar relationship to one enforced in nominal OOP languages. +A subclass cannot _remove_ a property of its base class, because doing so would destroy the natural subtype relationship between the derived class and its base. +Structural type systems simply identify this relationship implicitly by describing subtypes in terms of having properties of compatible types. + +#### Identical Types + +Another frequent source of surprise comes with identical types: + +```ts +class Car { + drive() { + // hit the gas + } +} +class Golfer { + drive() { + // hit the ball far + } +} + +// No error? +let w: Car = new Golfer(); +``` + +Again, this isn't an error because the _structures_ of these classes are the same. +While this may seem like a potential source of confusion, in practice, identical classes that shouldn't be related are not common. + +We'll learn more about how classes relate to each other in the Classes chapter. + +### Reflection + +OOP programmers are accustomed to being able to query the type of any value, even a generic one: + +```csharp +// C# +static void LogType() { + Console.WriteLine(typeof(T).Name); +} +``` + +Because TypeScript's type system is fully erased, information about e.g. the instantiation of a generic type parameter is not available at runtime. + +JavaScript does have some limited primitives like `typeof` and `instanceof`, but remember that these operators are still working on the values as they exist in the type-erased output code. +For example, `typeof (new Car())` will be `"object"`, not `Car` or `"Car"`. + +--- + +This is an overview, from here you should read [through the handbook](/docs/handbook/intro.html) or explore the [Playground examples](/play#show-examples) diff --git a/docs/documentation/ja/get-started/TS for the New Programmer.md b/docs/documentation/ja/get-started/TS for the New Programmer.md new file mode 100644 index 00000000..dae4be37 --- /dev/null +++ b/docs/documentation/ja/get-started/TS for the New Programmer.md @@ -0,0 +1,187 @@ +--- +title: TypeScript for the New Programmer +short: TS for the New Programmer +layout: docs +permalink: /docs/handbook/typescript-from-scratch.html +oneline: Learn TypeScript from scratch +--- + +Congratulations on choosing TypeScript as one of your first languages — you're already making good decisions! + +You've probably already heard that TypeScript is a "flavor" or "variant" of JavaScript. +The relationship between TypeScript (TS) and JavaScript (JS) is rather unique among modern programming languages, so learning more about this relationship will help you understand how TypeScript adds to JavaScript. + +## What is JavaScript? A Brief History + +JavaScript (also known as ECMAScript) started its life as a simple scripting language for browsers. +At the time it was invented, it was expected to be used for short snippets of code embedded in a web page — writing more than a few dozen lines of code would have been somewhat unusual. +Due to this, early web browsers executed such code pretty slowly. +Over time, though, JS became more and more popular, and web developers started using it to create interactive experiences. + +Web browser developers responded to this increased JS usage by optimizing their execution engines (dynamic compilation) and extending what could be done with it (adding APIs), which in turn made web developers use it even more. +On modern websites, your browser is frequently running applications that span hundreds of thousands of lines of code. +This is long and gradual growth of "the web", starting as a simple network of static pages, and evolving into a platform for rich _applications_ of all kinds. + +More than this, JS has become popular enough to be used outside the context of browsers, such as implementing JS servers using node.js. +The "run anywhere" nature of JS makes it an attractive choice for cross-platform development. +There are many developers these days that use _only_ JavaScript to program their entire stack! + +To summarize, we have a language that was designed for quick uses, and then grew to a full-fledged tool to write applications with millions of lines. +Every language has its own _quirks_ — oddities and surprises, and JavaScript's humble beginning makes it have _many_ of these. Some examples: + +- JavaScript's equality operator (`==`) _coerces_ its arguments, leading to unexpected behavior: + + ```js + if ("" == 0) { + // It is! But why?? + } + if (1 < x < 3) { + // True for *any* value of x! + } + ``` + +- JavaScript also allows accessing properties which aren't present: + + ```js + const obj = { width: 10, height: 15 }; + // Why is this NaN? Spelling is hard! + const area = obj.width * obj.heigth; + ``` + +Most programming languages would throw an error when these sorts of errors occur, some would do so during compilation — before any code is running. +When writing small programs, such quirks are annoying but manageable; when writing applications with hundreds or thousands of lines of code, these constant surprises are a serious problem. + +## TypeScript: A Static Type Checker + +We said earlier that some languages wouldn't allow those buggy programs to run at all. +Detecting errors in code without running it is referred to as _static checking_. +Determining what's an error and what's not based on the kinds of values being operated on is known as static _type_ checking. + +TypeScript checks a program for errors before execution, and does so based on the _kinds of values_, it's a _static type checker_. +For example, the last example above has an error because of the _type_ of `obj`. +Here's the error TypeScript found: + +```ts twoslash +// @errors: 2551 +const obj = { width: 10, height: 15 }; +const area = obj.width * obj.heigth; +``` + +### A Typed Superset of JavaScript + +How does TypeScript relate to JavaScript, though? + +#### Syntax + +TypeScript is a language that is a _superset_ of JavaScript: JS syntax is therefore legal TS. +Syntax refers to the way we write text to form a program. +For example, this code has a _syntax_ error because it's missing a `)`: + +```ts twoslash +// @errors: 1005 +let a = (4 +``` + +TypeScript doesn't consider any JavaScript code to be an error because of its syntax. +This means you can take any working JavaScript code and put it in a TypeScript file without worrying about exactly how it is written. + +#### Types + +However, TypeScript is a _typed_ superset, meaning that it adds rules about how different kinds of values can be used. +The earlier error about `obj.heigth` was not a _syntax_ error: it is an error of using some kind of value (a _type_) in an incorrect way. + +As another example, this is JavaScript code that you can run in your browser, and it _will_ log a value: + +```js +console.log(4 / []); +``` + +This syntactically-legal program logs `Infinity`. +TypeScript, though, considers division of number by an array to be a nonsensical operation, and will issue an error: + +```ts twoslash +// @errors: 2363 +console.log(4 / []); +``` + +It's possible you really _did_ intend to divide a number by an array, perhaps just to see what happens, but most of the time, though, this is a programming mistake. +TypeScript's type checker is designed to allow correct programs through while still catching as many common errors as possible. +(Later, we'll learn about settings you can use to configure how strictly TypeScript checks your code.) + +If you move some code from a JavaScript file to a TypeScript file, you might see _type errors_ depending on how the code is written. +These may be legitimate problems with the code, or TypeScript being overly conservative. +Throughout this guide we'll demonstrate how to add various TypeScript syntax to eliminate such errors. + +#### Runtime Behavior + +TypeScript is also a programming language that preserves the _runtime behavior_ of JavaScript. +For example, dividing by zero in JavaScript produces `Infinity` instead of throwing a runtime exception. +As a principle, TypeScript **never** changes the runtime behavior of JavaScript code. + +This means that if you move code from JavaScript to TypeScript, it is **guaranteed** to run the same way, even if TypeScript thinks that the code has type errors. + +Keeping the same runtime behavior as JavaScript is a foundational promise of TypeScript because it means you can easily transition between the two languages without worrying about subtle differences that might make your program stop working. + + + +#### Erased Types + +Roughly speaking, once TypeScript's compiler is done with checking your code, it _erases_ the types to produce the resulting "compiled" code. +This means that once your code is compiled, the resulting plain JS code has no type information. + +This also means that TypeScript never changes the _behavior_ of your program based on the types it inferred. +The bottom line is that while you might see type errors during compilation, the type system itself has no bearing on how your program works when it runs. + +Finally, TypeScript doesn't provide any additional runtime libraries. +Your programs will use the same standard library (or external libraries) as JavaScript programs, so there's no additional TypeScript-specific framework to learn. + + + +## Learning JavaScript and TypeScript + +We frequently see the question "Should I learn JavaScript or TypeScript?". + +The answer is that you can't learn TypeScript without learning JavaScript! +TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time. + +There are many, many resources available for programmers to learn JavaScript; you should _not_ ignore these resources if you're writing TypeScript. +For example, there are about 20 times more StackOverflow questions tagged `javascript` than `typescript`, but _all_ of the `javascript` questions also apply to TypeScript. + +If you find yourself searching for something like "how to sort a list in TypeScript", remember: **TypeScript is JavaScript's runtime with a compile-time type checker**. +The way you sort a list in TypeScript is the same way you do so in JavaScript. +If you find a resource that uses TypeScript directly, that's great too, but don't limit yourself to thinking you need TypeScript-specific answers for everyday questions about how to accomplish runtime tasks. + +--- + +From here, we'd recommend learning some of the JavaScript fundamentals (the [JavaScript guide at the Mozilla Web Docs](https://developer.mozilla.org/docs/Web/JavaScript/Guide) is a good starting point.) + +Once you're feeling comfortable, you can come back to read [TypeScript for JavaScript Programmers](/docs/handbook/typescript-in-5-minutes.html), then start on [the handbook](/docs/handbook/intro.html) or explore the [Playground examples](/play#show-examples). + + + From 41d811b268415a4312db1ba9d739976223d69dc7 Mon Sep 17 00:00:00 2001 From: Masato Urai Date: Sat, 27 Feb 2021 17:40:58 +0900 Subject: [PATCH 2/2] translate files into ja --- .../TS for Functional Programmers.md | 474 +++++++++--------- .../ja/get-started/TS for JS Programmers.md | 108 ++-- .../ja/get-started/TS for OOPers.md | 168 +++---- .../get-started/TS for the New Programmer.md | 156 +++--- 4 files changed, 453 insertions(+), 453 deletions(-) diff --git a/docs/documentation/ja/get-started/TS for Functional Programmers.md b/docs/documentation/ja/get-started/TS for Functional Programmers.md index 60945cd9..dd322f81 100644 --- a/docs/documentation/ja/get-started/TS for Functional Programmers.md +++ b/docs/documentation/ja/get-started/TS for Functional Programmers.md @@ -1,65 +1,65 @@ --- -title: TypeScript for Functional Programmers -short: TS for Functional Programmers +title: 関数型プログラマのための TypeScript +short: 関数型プログラマのための TS layout: docs -permalink: /docs/handbook/typescript-in-5-minutes-func.html -oneline: Learn TypeScript if you have a background in functional programming +permalink: /ja/docs/handbook/typescript-in-5-minutes-func.html +oneline: 関数型プログラミングのバックグラウンドから TypeScript を学ぶ --- -TypeScript began its life as an attempt to bring traditional object-oriented types -to JavaScript so that the programmers at Microsoft could bring -traditional object-oriented programs to the web. As it has developed, TypeScript's type -system has evolved to model code written by native JavaScripters. The -resulting system is powerful, interesting and messy. +TypeScript は、Microsoft のプログラマーが伝統的なオブジェクト指向のプログラムを Web に +導入できるようにするために、伝統的なオブジェクト指向の型を JavaScript に導入しようとする +試みから始まりました。開発が進むにつれ、TypeScript の型システムはネイティブ JavaScript の +プログラマーによって書かれたコードをモデル化するように進化してきました。 +結果としてこのシステムは強力で、興味深く、そして複雑なものとなります。 -This introduction is designed for working Haskell or ML programmers -who want to learn TypeScript. It describes how the type system of -TypeScript differs from Haskell's type system. It also describes -unique features of TypeScript's type system that arise from its -modelling of JavaScript code. +本入門書は、TypeScript を学びたいと考えている現役の +Haskell や ML プログラマー向けのものです。TypeScript の型システムが +Haskell の型システムとどのように異なるのかについて説明しています。 +また、JavaScript コードのモデル化から生じる TypeScript の +型システムのユニークな機能についても紹介します。 -This introduction does not cover object-oriented programming. In -practice, object-oriented programs in TypeScript are similar to those -in other popular languages with OO features. +ここでは、オブジェクト指向プログラミングについては扱いません。 +実際には TypeScript のオブジェクト指向のプログラムは、オブジェクト指向の +プログラム機能を持つ他の一般的な言語のものとよく似ています。 -## Prerequisites +## 前提 -In this introduction, I assume you know the following: +本入門書では、以下のことを知っていることを前提としています: -- How to program in JavaScript, the good parts. -- Type syntax of a C-descended language. +- JavaScript でプログラムする方法とその利点 +- C 系統言語の構文 -If you need to learn the good parts of JavaScript, read -[JavaScript: The Good Parts](http://shop.oreilly.com/product/9780596517748.do). -You may be able to skip the book if you know how to write programs in -a call-by-value lexically scoped language with lots of mutability and -not much else. -[R4RS Scheme](https://people.csail.mit.edu/jaffer/r4rs.pdf) is a good example. +JavaScript の利点について学ぶ必要がある場合は、 +[JavaScript: The Good Parts](http://shop.oreilly.com/product/9780596517748.do)を読んでください。 +ミュータブルな値以外をほとんど持たず、値渡しを行う +レキシカルスコープの言語でプログラムを記述する方法を知っている場合は、 +この本を読み飛ばすことができるかもしれません。 +[R4RS Scheme](https://people.csail.mit.edu/jaffer/r4rs.pdf)が良い例です。 -[The C++ Programming Language](http://www.stroustrup.com/4th.html) is -a good place to learn about C-style type syntax. Unlike C++, -TypeScript uses postfix types, like so: `x: string` instead of `string x`. +[The C++ Programming Language](http://www.stroustrup.com/4th.html)は +C スタイルの型の構文を学ぶには良い場所です。C++とは違い、 +TypeScript は`string x`ではなく、`x: string`のように、型を後ろにつけます。 -## Concepts not in Haskell +## Haskell にはないコンセプト -## Built-in types +## 組み込みの型 -JavaScript defines 8 built-in types: +JavaScript は 8 つの組み込み型を定義しています: -| Type | Explanation | -| ----------- | ------------------------------------------- | -| `Number` | a double-precision IEEE 754 floating point. | -| `String` | an immutable UTF-16 string. | -| `BigInt` | integers in the arbitrary precision format. | -| `Boolean` | `true` and `false`. | -| `Symbol` | a unique value usually used as a key. | -| `Null` | equivalent to the unit type. | -| `Undefined` | also equivalent to the unit type. | -| `Object` | similar to records. | +| 型 | 説明 | +| ----------- | ---------------------------------- | +| `Number` | IEEE 754 標準の倍精度浮動小数点数 | +| `String` | イミュータブルな UTF-16 文字列 | +| `BigInt` | 任意精度形式の整数 | +| `Boolean` | `true`および`false` | +| `Symbol` | 一般にキーとして使用される一意の値 | +| `Null` | Unit 型に相当する値 | +| `Undefined` | 同様に Unit 型に相当する値 | +| `Object` | レコード構造によく似た値 | -[See the MDN page for more detail](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures). +[詳しくは MDN のページをご確認ください](https://developer.mozilla.org/docs/Web/JavaScript/Data_structures). -TypeScript has corresponding primitive types for the built-in types: +TypeScript は組み込み型に対応するプリミティブな型を持っています: - `number` - `string` @@ -70,92 +70,92 @@ TypeScript has corresponding primitive types for the built-in types: - `undefined` - `object` -### Other important TypeScript types +### その他の重要な TypeScript の型 -| Type | Explanation | -| -------------- | ----------------------------------------------------------- | -| `unknown` | the top type. | -| `never` | the bottom type. | -| object literal | eg `{ property: Type }` | -| `void` | a subtype of `undefined` intended for use as a return type. | -| `T[]` | mutable arrays, also written `Array` | -| `[T, T]` | tuples, which are fixed-length but mutable | -| `(t: T) => U` | functions | +| 型 | 説明 | +| -------------------- | ----------------------------------------------------------- | +| `unknown` | 最上位の型 | +| `never` | 最下位の型 | +| オブジェクトリテラル | 例 `{ property: Type }` | +| `void` | 戻り値の型として使用するために設計された`undefined`の部分型 | +| `T[]` | ミュータブルな配列、`Array`とも記述可能 | +| `[T, T]` | 固定長であるがミュータブルであるタプル | +| `(t: T) => U` | 関数 | -Notes: +注意点: -1. Function syntax includes parameter names. This is pretty hard to get used to! +1. 関数の構文にはパラメータ名が含まれます。これは慣れるのがとても大変です! ```ts let fst: (a: any, b: any) => any = (a, b) => a; - // or more precisely: + // あるいはもっと正確に: let fst: (a: T, b: U) => T = (a, b) => a; ``` -2. Object literal type syntax closely mirrors object literal value syntax: +2. オブジェクトリテラル型の構文は、オブジェクトリテラルの値の構文を厳密に反映しています: ```ts let o: { n: number; xs: object[] } = { n: 1, xs: [] }; ``` -3. `[T, T]` is a subtype of `T[]`. This is different than Haskell, where tuples are not related to lists. +3. `[T, T]`は`T[]`の部分型です。これはタプルがリストに関係しない Haskell とは異なります。 -### Boxed types +### ボックス化された型 -JavaScript has boxed equivalents of primitive types that contain the -methods that programmers associate with those types. TypeScript -reflects this with, for example, the difference between the primitive -type `number` and the boxed type `Number`. The boxed types are rarely -needed, since their methods return primitives. +JavaScript にはプリミティブ型と等価であるボックス化された型があり、 +プログラマがそれらの型に関連付けるメソッドを持っています。TypeScript では、 +それらの違い、例えばプリミティブ型である`number`とボックス化された型である`Number` +の違いを反映しています。ボックス化された型のメソッドはプリミティブ型を +返すので、ボックス化された型が必要とされることはほとんどありません。 ```ts (1).toExponential(); -// equivalent to +// 上記は次と等しい Number.prototype.toExponential.call(1); ``` -Note that calling a method on a numeric literal requires it to be in -parentheses to aid the parser. +数値リテラルのメソッドを呼び出す際には、パーサに理解させるために +括弧で囲む必要があることに注意してください。 -## Gradual typing +## 漸進的な型付け -TypeScript uses the type `any` whenever it can't tell what the type of -an expression should be. Compared to `Dynamic`, calling `any` a type -is an overstatement. It just turns off the type checker -wherever it appears. For example, you can push any value into an -`any[]` without marking the value in any way: +TypeScript は、式の型がわからない場合は常に`any`型を使用します。 +`Dynamic`と比べると、`any`を型と呼ぶのはおおげさかもしれません。 +これは、型チェッカーを無効にしているだけです。例え +ば、任意の値を、値に何らかの方法で型をつけることなく +`any[]`にプッシュすることができます。 ```ts twoslash -// with "noImplicitAny": false in tsconfig.json, anys: any[] +// tsconfig.jsonで"noImplicitAny": falseの場合は、anys: any[]とします const anys = []; anys.push(1); anys.push("oh no"); anys.push({ anything: "goes" }); ``` -And you can use an expression of type `any` anywhere: +そして、`any`型の式はどこでも使うことができます: ```ts -anys.map(anys[1]); // oh no, "oh no" is not a function +anys.map(anys[1]); // oh no, "oh no"は関数ではありません ``` -`any` is contagious, too — if you initialise a variable with an -expression of type `any`, the variable has type `any` too. +また、`any`は伝染します — `any`型の式で初期化した場合、 +その変数も`any`型を持ちます。 ```ts -let sepsis = anys[0] + anys[1]; // this could mean anything +let sepsis = anys[0] + anys[1]; // どんな値でも入れることができます ``` -To get an error when TypeScript produces an `any`, use -`"noImplicitAny": true`, or `"strict": true` in `tsconfig.json`. +TypeScript が`any`を生成した時にエラーを発生させるには、`tsconfig.json`にて、 +`"noImplicitAny": true`あるいは`"strict": true`を使用します。 -## Structural typing +## 構造的型付け -Structural typing is a familiar concept to most functional -programmers, although Haskell and most MLs are not -structurally typed. Its basic form is pretty simple: +構造的型付けは、ほとんどの関数型プログラマには馴染みあるものですが、 +Haskell や多くの ML には構造的型付けはありません。その基本形は +とてもシンプルです: ```ts // @strict: false @@ -163,18 +163,18 @@ let o = { x: "hi", extra: 1 }; // ok let o2: { x: string } = o; // ok ``` -Here, the object literal `{ x: "hi", extra: 1 }` has a matching -literal type `{ x: string, extra: number }`. That -type is assignable to `{ x: string }` since -it has all the required properties and those properties have -assignable types. The extra property doesn't prevent assignment, it -just makes it a subtype of `{ x: string }`. +ここでは、オブジェクトリテラル`{ x: "hi", extra: 1 }`は、 +それにマッチするリテラル型`{ x: string, extra: number }`を持っています。 +この型は、必要とされるすべてのプロパティを持ち、それらのプロパティは +型に割り当て可能なので、`{ x: string }`に割り当てることができます。 +extra プロパティは、割り当てを妨げるものではなく、後者の型を`{ x: string }`の +部分型にします。 -Named types just give a name to a type; for assignability purposes -there's no difference between the type alias `One` and the interface -type `Two` below. They both have a property `p: string`. (Type aliases -behave differently from interfaces with respect to recursive -definitions and type parameters, however.) +名前付き型は、単に型に名前を付けるだけです。割り当てを目的とした場合 +以下の、型のエイリアスである`One`とインターフェース型である`Two`との間に +違いはありません。どちらも`p: string`プロパティを持ちます。(しかし、 +型のエイリアスは、再帰的定義や型パラメータに関して、インターフェースとは +異なるふるまいをします。) ```ts twoslash // @errors: 2322 @@ -193,15 +193,15 @@ two = new Three(); ## Unions -In TypeScript, union types are untagged. In other words, they are not -discriminated unions like `data` in Haskell. However, you can often -discriminate types in a union using built-in tags or other properties. +TypeScript では、Union 型はタグ付けされていません。言い換えると、 +Haskell の`data`のような区別された Union ではありません。しかし、 +組み込みのタグやその他のプロパティを使って Union 内の型を区別することができます。 ```ts twoslash function start( arg: string | string[] | (() => string) | { s: string } ): string { - // this is super common in JavaScript + // これはJavaScriptでは非常に一般的です if (typeof arg === "string") { return commonCase(arg); } else if (Array.isArray(arg)) { @@ -213,21 +213,21 @@ function start( } function commonCase(s: string): string { - // finally, just convert a string to another string + // 最後に、文字列を別の文字列に変換します return s; } } ``` -`string`, `Array` and `Function` have built-in type predicates, -conveniently leaving the object type for the `else` branch. It is -possible, however, to generate unions that are difficult to -differentiate at runtime. For new code, it's best to build only -discriminated unions. +`string`、`Array`そして`Function`は、組み込みの型述語があるため、 +オブジェクト型は`else`節のために残しておくと便利です。 +しかし、実行時に区別するのが難しい Union を生成することも +できてしまいます。新しいコードを記述するときは +区別可能な Union のみを作成するのがベストです。 -The following types have built-in predicates: +以下の型は組み込みの述語を持っています: -| Type | Predicate | +| 型 | 述語 | | --------- | ---------------------------------- | | string | `typeof s === "string"` | | number | `typeof n === "number"` | @@ -239,39 +239,39 @@ The following types have built-in predicates: | array | `Array.isArray(a)` | | object | `typeof o === "object"` | -Note that functions and arrays are objects at runtime, but have their -own predicates. +関数と配列は実行時にはオブジェクトですが、独自の述語を +持っていることに注意してください。 ### Intersections -In addition to unions, TypeScript also has intersections: +Union に加えて、TypeScript には Intersection もあります: ```ts twoslash type Combined = { a: number } & { b: string }; type Conflicting = { a: number } & { a: string }; ``` -`Combined` has two properties, `a` and `b`, just as if they had been -written as one object literal type. Intersection and union are -recursive in case of conflicts, so `Conflicting.a: number & string`. +`Combined`は、あたかも 1 つのオブジェクトリテラル型として記述されているかのように +`a`と`b`の 2 つのプロパティを持ちます。Intersection と Union は、 +競合があった場合には再帰的に処理されるので、`Conflicting.a`は、`number & string`となります。 -## Unit types +## Unit 型 -Unit types are subtypes of primitive types that contain exactly one -primitive value. For example, the string `"foo"` has the type -`"foo"`. Since JavaScript has no built-in enums, it is common to use a set of -well-known strings instead. Unions of string literal types allow -TypeScript to type this pattern: +Unit 型はプリミティブ型の部分型で、厳密な 1 つのプリミティブな値を +持ちます。例えば、文字列`"foo"`は、`"foo"`という型を持ちます。 +JavaScript には組み込みの Enum はないので、代わりに既知の文字列の +セットを使用するのが一般的です。文字列リテラル型の Union によって、 +TypeScript は以下のパターンに型をつけることができます: ```ts twoslash declare function pad(s: string, n: number, direction: "left" | "right"): string; pad("hi", 10, "left"); ``` -When needed, the compiler _widens_ — converts to a -supertype — the unit type to the primitive type, such as `"foo"` -to `string`. This happens when using mutability, which can hamper some -uses of mutable variables: +必要に応じて、コンパイラは、例えば`"foo"`から`string`など、 +Unit 型をプリミティブ型へ _拡張_ — 上位型に変換 — します。 +これはミュータブルな値を扱っている時に起こり、ミュータブル変数の使用を +妨げとなることがあります。 ```ts twoslash // @errors: 2345 @@ -281,15 +281,15 @@ let s = "right"; pad("hi", 10, s); // error: 'string' is not assignable to '"left" | "right"' ``` -Here's how the error happens: +どのようにしてエラーが発生するのかについて説明します: - `"right": "right"` -- `s: string` because `"right"` widens to `string` on assignment to a mutable variable. -- `string` is not assignable to `"left" | "right"` +- `"right"`は、ミュータブル変数に代入されると、`string`に拡張されるので`s: string`となります +- `string`は`"left" | "right"`に割り当てできません -You can work around this with a type annotation for `s`, but that -in turn prevents assignments to `s` of variables that are not of type -`"left" | "right"`. +`s`に型アノテーションを付けることで回避することができますが、 +これは同時に、`"left" | "right"`型を持たない変数の`s`への代入を +防いでもくれます ```ts twoslash declare function pad(s: string, n: number, direction: "left" | "right"): string; @@ -298,42 +298,42 @@ let s: "left" | "right" = "right"; pad("hi", 10, s); ``` -## Concepts similar to Haskell +## Haskell に似たコンセプト -## Contextual typing +## 文脈的型 -TypeScript has some obvious places where it can infer types, like -variable declarations: +TypeScript では、変数宣言などのように明らかに +型を推論できる箇所がいくつかあります: ```ts twoslash let s = "I'm a string!"; ``` -But it also infers types in a few other places that you may not expect -if you've worked with other C-syntax languages: +しかし、他の C 構文の言語を使ったことがある人にとっては +思いもよらないようなところでも型を推論します: ```ts twoslash declare function map(f: (t: T) => U, ts: T[]): U[]; let sns = map((n) => n.toString(), [1, 2, 3]); ``` -Here, `n: number` in this example also, despite the fact that `T` and `U` -have not been inferred before the call. In fact, after `[1,2,3]` has -been used to infer `T=number`, the return type of `n => n.toString()` -is used to infer `U=string`, causing `sns` to have the type -`string[]`. +上記で、呼び出し前に`T`と`U`は推論されていないにも関わらず、 +`n: number`となります。実際には、`[1,2,3]`を用いて +`T=number`と推論した後、`n => n.toString()`の +戻り値の型から`U=string`を推論します。これによって、 +`sns`は`string[]`型を持つようになります。 -Note that inference will work in any order, but intellisense will only -work left-to-right, so TypeScript prefers to declare `map` with the -array first: +推論は順番に関係なく動作しますが、インテリセンスは +左から右にしか動作せず、そのため TypeScript では配列を先頭にして +`map`を宣言する方が好ましいことに注意してください: ```ts twoslash declare function map(ts: T[], f: (t: T) => U): U[]; ``` -Contextual typing also works recursively through object literals, and -on unit types that would otherwise be inferred as `string` or -`number`. And it can infer return types from context: +文脈的型付けは、オブジェクトリテラルやそうでなければ`string`あるいは`number`と +推論されるような Unit 型に対しても、再帰的に動作します。また、 +文脈から戻り値の型を推論することができます: ```ts twoslash declare function run(thunk: (t: T) => void): T; @@ -342,47 +342,47 @@ let i: { inference: string } = run((o) => { }); ``` -The type of `o` is determined to be `{ inference: string }` because +`o`の型は、`{ inference: string }`であると判断されます。なぜなら -1. Declaration initialisers are contextually typed by the - declaration's type: `{ inference: string }`. -2. The return type of a call uses the contextual type for inferences, - so the compiler infers that `T={ inference: string }`. -3. Arrow functions use the contextual type to type their parameters, - so the compiler gives `o: { inference: string }`. +1. 宣言の初期化子は、宣言の型`{ inference: string }`によって + 文脈上の型が付けられる +2. 呼び出しの戻り値の型は、推論に文脈上の型を用いるので、 + コンパイラは`T={ inference: string }`と推論する +3. アロー関数は、文脈上の型を用いてパラメータに型を付けるため、 + コンパイラは`o: { inference: string }`を与える -And it does so while you are typing, so that after typing `o.`, you -get completions for the property `inference`, along with any other -properties you'd have in a real program. -Altogether, this feature can make TypeScript's inference look a bit -like a unifying type inference engine, but it is not. +そしてまた、この処理はあなたがタイピングしている間に行われるので、 +`o`を入力すると、実際のプログラムにあるようなプロパティに加えて +`inference`プロパティの補完が得られます。 +全体的に、この機能のおかげで TypeScript の推論は型を統一する推論エンジンのように +少し思えるかもしれませんが、そうではありません。 -## Type aliases +## 型エイリアス -Type aliases are mere aliases, just like `type` in Haskell. The -compiler will attempt to use the alias name wherever it was used in -the source code, but does not always succeed. +型エイリアスは、Haskell の`type`のような単なるエイリアスです。 +コンパイラはソースコードで使われているエイリアス名を使用しようとしますが、 +常に成功するとは限りません。 ```ts twoslash type Size = [number, number]; let x: Size = [101.1, 999.9]; ``` -The closest equivalent to `newtype` is a _tagged intersection_: +`newtype`に最も近いものは _タグ付きの Intersection_ です: ```ts type FString = string & { __compileTimeOnly: any }; ``` -An `FString` is just like a normal string, except that the compiler -thinks it has a property named `__compileTimeOnly` that doesn't -actually exist. This means that `FString` can still be assigned to -`string`, but not the other way round. +`FString`は、実際には存在しない`__compileTimeOnly`という +名前のプロパティを持っているとコンパイラが考えている以外は、 +通常の文字列です。つまり、`FString`は`string`に +割り当てることはできますが、その逆はできません。 -## Discriminated Unions +## 判別可能な Union -The closest equivalent to `data` is a union of types with discriminant -properties, normally called discriminated unions in TypeScript: +`data`に最も近いものは、判別式プロパティを持つ Union 型で、 +通常 TypeScript では、判別可能な Union と呼ばれます。 ```ts type Shape = @@ -391,11 +391,11 @@ type Shape = | { kind: "triangle"; x: number; y: number }; ``` -Unlike Haskell, the tag, or discriminant, is just a property in each -object type. Each variant has an identical property with a different -unit type. This is still a normal union type; the leading `|` is -an optional part of the union type syntax. You can discriminate the -members of the union using normal JavaScript code: +Haskell とは違い、タグ、つまり判別式は各オブジェクト型の +プロパティにすぎません。それぞれの型は、固有の Unit 型である +同一のプロパティを持っています。上記は通常の Union 型ですが、 +最も先頭の`|`は、Union 型構文では任意です。通常の JavaScript コードを +使って、Union のメンバを判別することができます ```ts twoslash type Shape = @@ -414,12 +414,12 @@ function area(s: Shape) { } ``` -Note that the return type of `area` is inferred to be `number` because -TypeScript knows the function is total. If some variant is not -covered, the return type of `area` will be `number | undefined` instead. +TypeScript は関数は合計であることを知っているので、`area`の戻り値の型は +`number`であると推論されることに注意してください。もし処理されないメンバがあれば、 +代わりに`area`の戻り値の型は`number | undefined`となるでしょう。 -Also, unlike Haskell, common properties show up in any union, so you -can usefully discriminate multiple members of the union: +また、Haskell とは異なり、共通プロパティはどの Union でも表示されます。 +そのため、共通プロパティを有効に使い、Union の複数のメンバを判別することができます。 ```ts twoslash type Shape = @@ -437,10 +437,10 @@ function height(s: Shape) { } ``` -## Type Parameters +## 型パラメータ -Like most C-descended languages, TypeScript requires declaration of -type parameters: +ほとんどの C 系統の言語と同じように、TypeScript は型パラメータの宣言を +必要とします: ```ts function liftArray(t: T): Array { @@ -448,9 +448,9 @@ function liftArray(t: T): Array { } ``` -There is no case requirement, but type parameters are conventionally -single uppercase letters. Type parameters can also be constrained to a -type, which behaves a bit like type class constraints: +大文字でなければならないということありませんが、型パラメータは慣習的に +大文字の 1 文字で表します。また、型パラメータは、型クラスの制約のように +ふるまう制約を型に与えることもできます。 ```ts function firstish(t1: T, t2: T): T { @@ -458,14 +458,14 @@ function firstish(t1: T, t2: T): T { } ``` -TypeScript can usually infer type arguments from a call based on the -type of the arguments, so type arguments are usually not needed. +TypeScript は通常、引数の型に基づいて呼び出しから型引数を推論することが +できるので、型引数は通常必要ありません。 -Because TypeScript is structural, it doesn't need type parameters as -much as nominal systems. Specifically, they are not needed to make a -function polymorphic. Type parameters should only be used to -_propagate_ type information, such as constraining parameters to be -the same type: +TypeScript は構造型であるため、公称型システムほど、型パラメータを +必要としません。具体的には、関数のポリモーフィックを +作成するためには必要としません。型パラメータは、パラメータが +同じ型であるように制約するなど、型情報を伝播するために +使われるべきです。 ```ts function length>(t: T): number {} @@ -473,31 +473,31 @@ function length>(t: T): number {} function length(t: ArrayLike): number {} ``` -In the first `length`, T is not necessary; notice that it's only -referenced once, so it's not being used to constrain the type of the -return value or other parameters. +最初の`length`では、T は必要ではありません。一度しか +参照されていないので、戻り値や他のパラメータの制約に +使われてはいないことに注意してください。 -### Higher-kinded types +### 高階型 -TypeScript does not have higher kinded types, so the following is not legal: +TypeScript には高階型はないので、以下は正しくありません: ```ts function length, U>(m: T) {} ``` -### Point-free programming +### ポイントフリープログラミング -Point-free programming — heavy use of currying and function -composition — is possible in JavaScript, but can be verbose. -In TypeScript, type inference often fails for point-free programs, so -you'll end up specifying type parameters instead of value parameters. The -result is so verbose that it's usually better to avoid point-free -programming. +ポイントフリープログラミング — カリー化や関数合成の多用 — は、 +JavaScript でも可能ですが、冗長になる可能性があります。TypeScript では、 +ポイントフリープログラムに対する型推論がよく失敗するため、値パラメータの +代わりに、型パラメータを指定することになります。その結果、 +非常に冗長になるので、通常はポイントフリースタイルを避けたほうが +良いでしょう。 -## Module system +## モジュールシステム -JavaScript's modern module syntax is a bit like Haskell's, except that -any file with `import` or `export` is implicitly a module: +JavaScript のモダンなモジュール構文は、`import`や`export`を持つファイルは +暗黙的にモジュールとなるという点を除いては、Haskell に少し似ています。 ```ts import { value, Type } from "npm-package"; @@ -505,14 +505,14 @@ import { other, Types } from "./local-package"; import * as prefix from "../lib/third-package"; ``` -You can also import commonjs modules — modules written using node.js' -module system: +commonjs モジュール(node.js で記述されたモジュール)をインポートすることも +できます: ```ts import f = require("single-function-package"); ``` -You can export with an export list: +エクスポートリストを使用するか: ```ts export { f }; @@ -520,24 +520,24 @@ export { f }; function f() { return g(); } -function g() {} // g is not exported +function g() {} // gはエクスポートされません ``` -Or by marking each export individually: +あるいは個別にエクスポートして、エクスポートすることができます: ```ts export function f { return g() } function g() { } ``` -The latter style is more common but both are allowed, even in the same -file. +後者のスタイルのほうが一般的ですが、両方とも、同じファイル内であっても +可能です。 -## `readonly` and `const` +## `readonly`と`const` -In JavaScript, mutability is the default, although it allows variable -declarations with `const` to declare that the _reference_ is -immutable. The referent is still mutable: +JavaScript では、デフォルトでは値はミュータブルですが、 +`const`を使って変数を宣言すると、その _参照_ はイミュータブルとなります。 +参照元は依然、ミュータブルです: ```js const a = [1, 2, 3]; @@ -545,18 +545,18 @@ a.push(102); // ): a[0] = 101; // D: ``` -TypeScript additionally has a `readonly` modifier for properties. +TypeScript には、これに加え、プロパティに使用する`readonly`修飾子を備えています。 ```ts interface Rx { readonly x: number; } let rx: Rx = { x: 1 }; -rx.x = 12; // error +rx.x = 12; // エラー ``` -It also ships with a mapped type `Readonly` that makes -all properties `readonly`: +また、すべてのプロパティを`readonly`にする Mapped Type の`Readonly`も +導入されました: ```ts interface X { @@ -566,9 +566,9 @@ let rx: Readonly = { x: 1 }; rx.x = 12; // error ``` -And it has a specific `ReadonlyArray` type that removes -side-affecting methods and prevents writing to indices of the array, -as well as special syntax for this type: +さらに、副作用のあるメソッドを排除し、配列のインデックスへの +書き込みを禁止する特別な`ReadonlyArray`型と、 +この型のための特別な構文があります。 ```ts let a: ReadonlyArray = [1, 2, 3]; @@ -577,8 +577,8 @@ a.push(102); // error b[0] = 101; // error ``` -You can also use a const-assertion, which operates on arrays and -object literals: +配列やオブジェクトリテラルに対して、const を使ったアサーションを +使うこともできます: ```ts let a = [1, 2, 3] as const; @@ -586,12 +586,12 @@ a.push(102); // error a[0] = 101; // error ``` -However, none of these options are the default, so they are not -consistently used in TypeScript code. +しかし、これらの選択肢はどれもデフォルトではなく、そのために +TypeScript のコードで常に使用されているというわけではありません。 -## Next Steps +## 次のステップ -This doc is a high level overview of the syntax and types you would use in everyday code. From here you should: +本ドキュメントは、日常のコードで使用するであろう構文と型についての高度な概要です。ここから次に進みましょう -- Read the full Handbook [from start to finish](/docs/handbook/intro.html) (30m) -- Explore the [Playground examples](/play#show-examples). +- ハンドブックを[始めから終わりまで](/docs/handbook/intro.html)読む(30 分) +- [Playground の例](/play#show-examples)を探る diff --git a/docs/documentation/ja/get-started/TS for JS Programmers.md b/docs/documentation/ja/get-started/TS for JS Programmers.md index f35ba88f..db4e4fed 100644 --- a/docs/documentation/ja/get-started/TS for JS Programmers.md +++ b/docs/documentation/ja/get-started/TS for JS Programmers.md @@ -1,38 +1,38 @@ --- -title: TypeScript for JavaScript Programmers -short: TypeScript for JS Programmers +title: JavaScript プログラマのための TypeScript +short: JS プログラマのための TypeScript layout: docs -permalink: /docs/handbook/typescript-in-5-minutes.html -oneline: Learn how TypeScript extends JavaScript +permalink: /ja/docs/handbook/typescript-in-5-minutes.html +oneline: TypeScript がどのように JavaScript を拡張するのか学ぶ --- -TypeScript stands in an unusual relationship to JavaScript. TypeScript offers all of JavaScript's features, and an additional layer on top of these: TypeScript's type system. +TypeScript は、JavaScript と奇妙な関係にあります。TypeScript は、JavaScript のすべての機能を提供し、その上に、TypeScript の型システムというレイヤーを追加します。 -For example, JavaScript provides language primitives like `string`, `number`, and `object`, but it doesn't check that you've consistently assigned these. TypeScript does. +例えば JavaScript には`string`や`number`、`object`といった言語プリミティブがありますが、これらが矛盾なく代入されているかどうかは検証しません。しかし、TypeScript は検証します。 -This means that your existing working JavaScript code is also TypeScript code. The main benefit of TypeScript is that it can highlight unexpected behavior in your code, lowering the chance of bugs. +これは既存の動作する JavaScript コードも TypeScript のコードであることを意味します。TypeScript の主な利点は、コード内の予期せぬ動作を強調表示し、バグの可能性を減らすことができることです。 -This tutorial provides a brief overview of TypeScript, focusing on its type system. +本チュートリアルでは TypeScript の型システムに焦点を当てて、TypeScript の簡単な概要を説明します。 -## Types by Inference +## 推論による型 -TypeScript knows the JavaScript language and will generate types for you in many cases. -For example in creating a variable and assigning it to a particular value, TypeScript will use the value as its type. +TypeScript は JavaScript 言語を理解しており、多くのケースで型を生成します。 +例えば、変数を作成して特定の値に代入する場合、TypeScript はその値を型として使用します。 ```ts twoslash let helloWorld = "Hello World"; // ^? ``` -By understanding how JavaScript works, TypeScript can build a type-system that accepts JavaScript code but has types. This offers a type-system without needing to add extra characters to make types explicit in your code. That's how TypeScript knows that `helloWorld` is a `string` in the above example. +JavaScript がどのように動作するのか理解することで、TypeScript は JavaScript コードを受け入れながらも型を持つ型システムを構築することができます。これにより、コードの中で型を明示するために余計な文字を追加することのない型システムを提供することができます。このようにして、上記の例では TypeScript は`helloWorld`が`string`であるということを認識します。 -You may have written JavaScript in Visual Studio Code, and had editor auto-completion. Visual Studio Code uses TypeScript under the hood to make it easier to work with JavaScript. +Visual Studio Code で JavaScript を書いていて、エディタの自動補完を使ったことがあるかもしれません。Visual Studio Code は、JavaScript での作業を簡単にするために内部で TypeScript を使用しています。 -## Defining Types +## 型の定義 -You can use a wide variety of design patterns in JavaScript. However, some design patterns make it difficult for types to be inferred automatically (for example, patterns that use dynamic programming). To cover these cases, TypeScript supports an extension of the JavaScript language, which offers places for you to tell TypeScript what the types should be. +JavaScript で使用できるデザインパターンは多岐にわたります。しかし、型を自動的に推論することを難しくしてしまうデザインパターン(例えば、動的プログラミングを使用するパターンなど)もあります。このようなケースをカバーするために、TypeScript は JavaScript 言語の拡張機能をサポートし、TypeScript に型が何であるかを伝えるためのスペースを確保しています。 -For example, to create an object with an inferred type which includes `name: string` and `id: number`, you can write: +例えば、`name: string`と`id: number`を含む、推論された型を持つオブジェクトを作成するには、次のように記述できます: ```ts twoslash const user = { @@ -41,7 +41,7 @@ const user = { }; ``` -You can explicitly describe this object's shape using an `interface` declaration: +このオブジェクトの形状は、`interface`宣言を使って明示的に記述することができます: ```ts twoslash interface User { @@ -50,7 +50,7 @@ interface User { } ``` -You can then declare that a JavaScript object conforms to the shape of your new `interface` by using syntax like `: TypeName` after a variable declaration: +変数宣言の後に`: TypeName`といった構文を使うことで、JavaScript オブジェクトが新しい`interface`の形状に適合することを宣言することができます。 ```ts twoslash interface User { @@ -64,7 +64,7 @@ const user: User = { }; ``` -If you provide an object that doesn't match the interface you have provided, TypeScript will warn you: +もし定義したインターフェースと一致しないオブジェクトを作成した場合は、TypeScript は警告を発します: ```ts twoslash // @errors: 2322 @@ -79,7 +79,7 @@ const user: User = { }; ``` -Since JavaScript supports classes and object-oriented programming, so does TypeScript. You can use an interface declaration with classes: +JavaScript はクラスおよびオブジェクト指向プログラミングをサポートしているため、TypeScript も同様にサポートしています。そのためクラスを使ったインターフェース宣言を使うことができます: ```ts twoslash interface User { @@ -100,7 +100,7 @@ class UserAccount { const user: User = new UserAccount("Murphy", 1); ``` -You can use interfaces to annotate parameters and return values to functions: +インターフェースを使ってパラメータや関数の戻り値に型注釈を付けることができます: ```ts twoslash // @noErrors @@ -118,25 +118,25 @@ function deleteUser(user: User) { } ``` -There are already a small set of primitive types available in JavaScript: `boolean`, `bigint`, `null`, `number`, `string`, `symbol`, `object`, and `undefined`, which you can use in an interface. TypeScript extends this list with a few more, such as `any` (allow anything), [`unknown`](/play#example/unknown-and-never) (ensure someone using this type declares what the type is), [`never`](/play#example/unknown-and-never) (it's not possible that this type could happen), and `void` (a function which returns `undefined` or has no return value). +`boolean`、`bigint`、`null`、`number`、`string`、`symbol`、`object`および`undefined`という JavaScript で利用可能なプリミティブな型がわずかですが存在しており、これらはインターフェース内で使用できます。TypeScript はこれらを少し拡張しています。例えば、`any`(何でも許可する)や、[`unknown`](/play#example/unknown-and-never)(この型を使う人に、型が何であるかを宣言させる)、[`never`](/play#example/unknown-and-never) (この型が生じる可能性がない)、そして`void` (`undefined`を返す、あるいは戻り値がない関数)があります。 -You'll see that there are two syntaxes for building types: [Interfaces and Types](/play/?e=83#example/types-vs-interfaces). You should prefer `interface`. Use `type` when you need specific features. +型を構築するための構文は[インターフェースと型エイリアス](/play/?e=83#example/types-vs-interfaces)の 2 つあります。基本は`interface`を、特定の機能が必要な場合は`type`を使うと良いでしょう。 -## Composing Types +## 型の組み合わせ -With TypeScript, you can create complex types by combining simple ones. There are two popular ways to do so: with Unions, and with Generics. +TypeScript では、単純な型を組み合わせて複雑な型を作ることができます。よく用いられる方法としては、Union を使う方法とジェネリクスを使う方法の 2 つがあります。 ### Unions -With a union, you can declare that a type could be one of many types. For example, you can describe a `boolean` type as being either `true` or `false`: +Union では、型を多くの型のうちの一つであると宣言することができます。例えば、`boolean`型を`true`あるは`false`のどちらかであると記述することができます: ```ts twoslash type MyBool = true | false; ``` -_Note:_ If you hover over `MyBool` above, you'll see that it is classed as `boolean`. That's a property of the Structural Type System. More on this below. +_注意:_ 上記の`MyBool`にマウスカーソルを合わせると、`boolean`に分類されていることが分かります。これは構造的型システムの特性です。このことについては後述します。 -A popular use-case for union types is to describe the set of `string`s or `number`s [literal](/docs/handbook/literal-types.html) that a value is allowed to be: +Union 型は、ある値が許可される`string`や`number`の[リテラル](/docs/handbook/literal-types.html)の集合を記述するためによく使用されます。 ```ts twoslash type WindowStates = "open" | "closed" | "minimized"; @@ -144,7 +144,7 @@ type LockStates = "locked" | "unlocked"; type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9; ``` -Unions provide a way to handle different types too. For example, you may have a function that takes an `array` or a `string`: +Union では、異なる型を扱うこともできます。例えば、`array`あるいは`string`を受け取る関数があるかもしれません: ```ts twoslash function getLength(obj: string | string[]) { @@ -152,9 +152,9 @@ function getLength(obj: string | string[]) { } ``` -To learn the type of a variable, use `typeof`: +変数の型を知るには`typeof`を使用します: -| Type | Predicate | +| 型 | 述語 | | --------- | ---------------------------------- | | string | `typeof s === "string"` | | number | `typeof n === "number"` | @@ -163,7 +163,7 @@ To learn the type of a variable, use `typeof`: | function | `typeof f === "function"` | | array | `Array.isArray(a)` | -For example, you can make a function return different values depending on whether it is passed a string or an array: +例えば、関数に、文字列あるいは配列を渡すかどうかによって異なる値を返すようにすることができます。 ```ts twoslash @@ -177,9 +177,9 @@ function wrapInArray(obj: string | string[]) { } ``` -### Generics +### ジェネリクス -Generics provide variables to types. A common example is an array. An array without generics could contain anything. An array with generics can describe the values that the array contains. +ジェネリクスは型に変数を提供します。よく使われるのは配列です。ジェネリクスを使わない配列は任意の値を含むことができます。ジェネリクスを使った配列は、その配列が含むことのできる値を記述できます。 ```ts type StringArray = Array; @@ -187,7 +187,7 @@ type NumberArray = Array; type ObjectWithNameArray = Array<{ name: string }>; ``` -You can declare your own types that use generics: +ジェネリクスを使用する独自の型を宣言することができます: ```ts twoslash // @errors: 2345 @@ -196,22 +196,22 @@ interface Backpack { get: () => Type; } -// This line is a shortcut to tell TypeScript there is a -// constant called `backpack`, and to not worry about where it came from. +// 次の行はTypeScriptに`backpack`という定数があることを伝え、 +// それがどこで定義されているのかを気にしないように伝える省略表現です。 declare const backpack: Backpack; -// object is a string, because we declared it above as the variable part of Backpack. +// 上記でBackpackの変数部分として文字列を宣言したため、objectは文字列です。 const object = backpack.get(); -// Since the backpack variable is a string, you can't pass a number to the add function. +// 変数部分は文字列なので、add関数に数値を渡すことはできません。 backpack.add(23); ``` -## Structural Type System +## 構造的型システム -One of TypeScript's core principles is that type checking focuses on the _shape_ that values have. This is sometimes called "duck typing" or "structural typing". +TypeScript の中心となる原則の一つは、型チェックは値が持つ _形状_ に焦点を当てるというものです。これは"ダックタイピング"や、あるいは"構造的型付け"と呼ばれることがあります。 -In a structural type system, if two objects have the same shape, they are considered to be of the same type. +構造的型システムでは、2 つのオブジェクトが同じ形状ならば、それらは同じ型であるとみなされます。 ```ts twoslash interface Point { @@ -223,14 +223,14 @@ function logPoint(p: Point) { console.log(`${p.x}, ${p.y}`); } -// logs "12, 26" +// "12, 26"と出力されます const point = { x: 12, y: 26 }; logPoint(point); ``` -The `point` variable is never declared to be a `Point` type. However, TypeScript compares the shape of `point` to the shape of `Point` in the type-check. They have the same shape, so the code passes. +`point`変数は`Point`型として宣言されていません。しかし、TypeScript は型チェックにおいて、`point`の形状と`Point`の形状を比較します。2 つは同じ形状であるため、コードは型チェックをパスします。 -The shape-matching only requires a subset of the object's fields to match. +オブジェクトのフィールドの部分集合が一致するだけでも形状は一致しているとみなされます ```ts twoslash // @errors: 2345 @@ -244,16 +244,16 @@ function logPoint(p: Point) { } // ---cut--- const point3 = { x: 12, y: 26, z: 89 }; -logPoint(point3); // logs "12, 26" +logPoint(point3); // "12, 26"と出力されます const rect = { x: 33, y: 3, width: 30, height: 80 }; -logPoint(rect); // logs "33, 3" +logPoint(rect); // "33, 3"と出力されます const color = { hex: "#187ABF" }; logPoint(color); ``` -There is no difference between how classes and objects conform to shapes: +クラスおよびオブジェクトがどのように形状に一致するかについて違いはありません: ```ts twoslash // @errors: 2345 @@ -277,14 +277,14 @@ class VirtualPoint { } const newVPoint = new VirtualPoint(13, 56); -logPoint(newVPoint); // logs "13, 56" +logPoint(newVPoint); // "13, 56"と出力されます ``` -If the object or class has all the required properties, TypeScript will say they match, regardless of the implementation details. +オブジェクトやクラスが必要なプロパティをすべて持っていれば、実装の詳細に関わらず、TypeScript はそれらが一致しているとみなします。 -## Next Steps +## 次のステップ -This was a brief overview of the syntax and tools used in everyday TypeScript. From here, you can: +以上、TypeScript でよく使われる構文とツールについての簡単な概要でした。ここから以下のステップに進むことができます: -- Read the full Handbook [from start to finish](/docs/handbook/intro.html) (30m) -- Explore the [Playground examples](/play#show-examples). +- ハンドブックを[始めから終わりまで](/docs/handbook/intro.html)読む (30 分) +- [Playground の例](/play#show-examples)を探る diff --git a/docs/documentation/ja/get-started/TS for OOPers.md b/docs/documentation/ja/get-started/TS for OOPers.md index a7ba8007..2477d762 100644 --- a/docs/documentation/ja/get-started/TS for OOPers.md +++ b/docs/documentation/ja/get-started/TS for OOPers.md @@ -1,86 +1,86 @@ --- -title: TypeScript for Java/C# Programmers -short: TS for Java/C# Programmers +title: Java/C# プログラマのための TypeScript +short: Java/C# プログラマのための TS layout: docs -permalink: /docs/handbook/typescript-in-5-minutes-oop.html -oneline: Learn TypeScript if you have a background in object-oriented languages +permalink: /ja/docs/handbook/typescript-in-5-minutes-oop.html +oneline: オブジェクト指向言語のバックグラウンドから TypeScript を学ぶ --- -TypeScript is a popular choice for programmers accustomed to other languages with static typing, such as C# and Java. +TypeScript は、C# や Java といった静的型付けを持つ他の言語に慣れているプログラマに人気の選択肢です。 -TypeScript's type system offers many of the same benefits, such as better code completion, earlier detection of errors, and clearer communication between parts of your program. -While TypeScript provides many familiar features for these developers, it's worth stepping back to see how JavaScript (and therefore TypeScript) differ from traditional OOP languages. -Understanding these differences will help you write better JavaScript code, and avoid common pitfalls that programmers who go straight from C#/Java to TypeScript may fall in to. +TypeScript の型システムには、コードの補完性の向上、エラーの早期発見、プログラムの各部分間のコミュニケーションの明確化など、多くの利点があります。 +TypeScript は C#や Java の開発者にとってはおなじみの機能を多く提供していますが、JavaScript(そして、それ故に TypeScript)が従来のオブジェクト指向プログラミング言語とどのように異なるのか、一歩引いて見てみる価値があります。 +これらの違いを理解することで、より良い JavaScript コードを書くことができ、C#/Java から TypeScript に直行するプログラマが陥りがちな落とし穴を避けることができます。 -## Co-learning JavaScript +## JavaScript との相互学習 -If you're familiar with JavaScript already but are primarily a Java or C# programmer, this introductory page can help explain some of the common misconceptions and pitfalls you might be susceptible to. -Some of the ways that TypeScript models types are quite different from Java or C#, and it's important to keep these in mind when learning TypeScript. +JavaScript にはすでに慣れているが、本来 Java や C# のプログラマである場合、本入門ページは陥りやすいよくある誤解や落とし穴について理解する助けになるでしょう。 +TypeScript が型をモデル化する方法の中には、Java や C# とは全く異なるものがあり、TypeScript を学ぶ際にはこうした点に留意しておくことが重要です。 -If you're a Java or C# programmer that is new to JavaScript in general, we recommend learning a little bit of JavaScript _without_ types first to understand JavaScript's runtime behaviors. -Because TypeScript doesn't change how your code _runs_, you'll still have to learn how JavaScript works in order to write code that actually does something! +あなたが Java や C# のプログラマで、全般的に JavaScript に不慣れである場合は、JavaScript の実行時の動作を理解するために型の _ない_ JavaScript を最初に少しだけ学ぶことをおすすめします。 +TypeScript はコードの _動作_ を変更しないため、実際に何かを行うコードを書くためには、やはり JavaScript がどのように動作するのかについて学ぶ必要があるからです! -It's important to remember that TypeScript uses the same _runtime_ as JavaScript, so any resources about how to accomplish specific runtime behavior (converting a string to a number, displaying an alert, writing a file to disk, etc.) will always apply equally well to TypeScript programs. -Don't limit yourself to TypeScript-specific resources! +TypeScript は JavaScript と同じ _ランタイム_ を使用しているため、特定の実行時の動作(文字列を数値に変換する、アラートを表示する、ファイルをディスクに書き込むなど)を実現する手段はどんなものでも、常に TypeScript プログラムにも等しく適用されるということを覚えておくことが重要です。 +TypeScript 特有の方法に思考を制限しないようにしましょう! -## Rethinking the Class +## クラスの再考 -C# and Java are what we might call _mandatory OOP_ languages. -In these languages, the _class_ is the basic unit of code organization, and also the basic container of all data _and_ behavior at runtime. -Forcing all functionality and data to be held in classes can be a good domain model for some problems, but not every domain _needs_ to be represented this way. +C# と Java は、_強制オブジェクト指向プログラミング_ 言語と呼ばれるものです。 +これらの言語では、 _クラス_ はコード編成の基本的な単位であり、すべてのデータ _および_ 実行時の動作の基本的なコンテナでもあります。 +すべての機能とデータを強制的にクラスに保持させることは、問題を解決するためには適したドメインモデルとなることもありますが、すべてのドメインがこのように表現される _必要_ はありません。 -### Free Functions and Data +### 自由関数とデータ -In JavaScript, functions can live anywhere, and data can be passed around freely without being inside a pre-defined `class` or `struct`. -This flexibility is extremely powerful. -"Free" functions (those not associated with a class) working over data without an implied OOP hierarchy tends to be the preferred model for writing programs in JavaScript. +JavaScript では、関数はどこにでも存在できますし、また、データは事前に定義された`class`や`struct`の中に入ることなく、自由に渡すことができます。 +この柔軟性は非常に強力です。 +"自由"関数(クラスに関連付けられていない関数)は、暗黙的なオブジェクト指向プログラミングの階層構造を持たないデータ上で動作するため、JavaScript でプログラムを記述する際には多くのケースで好ましいモデルとなります。 -### Static Classes +### 静的クラス -Additionally, certain constructs from C# and Java such as singletons and static classes are unnecessary in TypeScript. +さらに、シングルトンや静的クラスといった C# と Java の構造体は TypeScript では不要です。 -## OOP in TypeScript +## TypeScript でのオブジェクト指向プログラミング -That said, you can still use classes if you like! -Some problems are well-suited to being solved by a traditional OOP hierarchy, and TypeScript's support for JavaScript classes will make these models even more powerful. -TypeScript supports many common patterns such as implementing interfaces, inheritance, and static methods. +とは言え、クラスを使用することもできます。 +伝統的なオブジェクト指向プログラミングの階層構造で解決するのに適した問題もあり、TypeScript の JavaScript クラスのサポートにより、こうしたモデルをさらに強力なものになります。 +TypeScript は、インターフェースの実装や静的メソッドなどの多くの一般的なパターンをサポートします。 -We'll cover classes later in this guide. +クラスについては本ガイドの後半で説明します。 -## Rethinking Types +## 型の再考 -TypeScript's understanding of a _type_ is actually quite different from C# or Java's. -Let's explore some differences. +TypeScript における _型_ の理解は、C# や Java のそれとは実際大きく違います。 +いくつか違いを探ってみましょう。 -### Nominal Reified Type Systems +### 名目具体化型システム -In C# or Java, any given value or object has one exact type - either `null`, a primitive, or a known class type. -We can call methods like `value.GetType()` or `value.getClass()` to query the exact type at runtime. -The definition of this type will reside in a class somewhere with some name, and we can't use two classes with similar shapes in lieu of each other unless there's an explicit inheritance relationship or commonly-implemented interface. +C# や Java では、与えられた値やオブジェクトは`null`、プリミティブ、あるいは既知のクラス型のいずれかの厳密な型を持ちます。 +`value.GetType()`や`value.getClass()`といったメソッドを呼び出し、実行時にその厳密な型を問い合わせることができます。 +この型の定義はある名前でクラスのどこかに存在しており、明示的な継承関係あるいは共通に実装されたインターフェースがない限り、似たような形をしていようとも 2 つのクラスをお互いに代用して使うことができません。 -These aspects describe a _reified, nominal_ type system. -The types we wrote in the code are present at runtime, and the types are related via their declarations, not their structures. +これは _具体化、名目的_ 型システムの特徴を表しています。 +コードに記述した型はランタイムに存在し、型は構造体ではなく宣言を通して関連付けられています。 -### Types as Sets +### 集合体としての型 -In C# or Java, it's meaningful to think of a one-to-one correspondence between runtime types and their compile-time declarations. +C# や Java では、ランタイムの型とコンパイル時の宣言の間に一対一の対応関係があると考えることに意味があります。 -In TypeScript, it's better to think of a type as a _set of values_ that share something in common. -Because types are just sets, a particular value can belong to _many_ sets at the same time. +TypeScript では、型は何かしらの共通点がある _値の集合体_ として考える方が良いでしょう。 +型は単なる集合体なので、特定の値は同時に _多くの_ 集合に属することができます。 -Once you start thinking of types as sets, certain operations become very natural. -For example, in C#, it's awkward to pass around a value that is _either_ a `string` or `int`, because there isn't a single type that represents this sort of value. +型を集合体と考えるようになると、特定の操作がとても自然に受け入れられるようになります。 +例えば、C# では、`string`や`int`のうち _どちらか_ である値を渡すのは不自然です。なぜならこの種の値を表す単一の型が存在しないからです。 -In TypeScript, this becomes very natural once you realize that every type is just a set. -How do you describe a value that either belongs in the `string` set or the `number` set? -It simply belongs to the _union_ of those sets: `string | number`. +TypeScript では、すべての型は単なる集合体であると理解すると、この操作はとても自然なことになります。 +では、`string`の集合あるいは`number`の集合、どちらかに属する値はどのように記述すれば良いでしょう? +この値は単に 2 つの集合の _Union_ (`string | number`)に属しています。 -TypeScript provides a number of mechanisms to work with types in a set-theoretic way, and you'll find them more intuitive if you think of types as sets. +TypeScript は、集合理論的な方法で型を扱うメカニズムを多く提供しており、型を集合であると考えると、直感的に使用できるようになるでしょう。 -### Erased Structural Types +### 削除される構造的型 -In TypeScript, objects are _not_ of a single exact type. -For example, if we construct an object that satisfies an interface, we can use that object where that interface is expected even though there was no declarative relationship between the two. +TypeScript では、オブジェクトは単一の厳密な型では _ありません_。 +例えば、あるインターフェースを満たすオブジェクトを構築した場合、2 つの間に宣言的な関係がなかったとしても、そのインターフェースが期待される場所でオブジェクトを使用することができます。 ```ts twoslash interface Pointlike { @@ -109,70 +109,70 @@ logPoint(obj); logName(obj); ``` -TypeScript's type system is _structural_, not nominal: We can use `obj` as a `Pointlike` because it has `x` and `y` properties that are both numbers. -The relationships between types are determined by the properties they contain, not whether they were declared with some particular relationship. +TypeScript の型システムは _構造的_ であり名目的ではありません。つまり、`obj`は`x`と`y`プロパティを持ち、どちらも数値であるため、`Pointlike`として使用することができます。 +型と型の関係は、特定の関係で宣言されたかどうかではなく、それらの型に含まれる含まれるプロパティによって決定されます。 -TypeScript's type system is also _not reified_: There's nothing at runtime that will tell us that `obj` is `Pointlike`. -In fact, the `Pointlike` type is not present _in any form_ at runtime. +TypeScript の型システムは、_具体化的_ でもありません。実行時に`obj`が`Pointlike`であることを教えてくれるものは何もありません。 +実際に、`Pointlike`型は実行時には _どのような形でも_ 存在することはありません。 -Going back to the idea of _types as sets_, we can think of `obj` as being a member of both the `Pointlike` set of values and the `Named` set of values. +_集合としての型_ という考えに戻ると、`obj`は`Pointlike`という値の集合と`Named`という値の集合の両方の構成要素であると考えることができます。 -### Consequences of Structural Typing +### 構造的型付けの結果 -OOP programmers are often surprised by two particular aspects of structural typing. +オブジェクト指向のプログラマは、構造的型付けの 2 つの独特な側面にしばしば驚かされます。 -#### Empty Types +#### 空の型 -The first is that the _empty type_ seems to defy expectation: +1 つ目は _空の型_ が予想に反しているように見えることです: ```ts twoslash class Empty {} function fn(arg: Empty) { - // do something? + // 何かを行う } -// No error, but this isn't an 'Empty' ? +// エラーが出ませんが、これは'Empty'ではないのでは? fn({ k: 10 }); ``` -TypeScript determines if the call to `fn` here is valid by seeing if the provided argument is a valid `Empty`. -It does so by examining the _structure_ of `{ k: 10 }` and `class Empty { }`. -We can see that `{ k: 10 }` has _all_ of the properties that `Empty` does, because `Empty` has no properties. -Therefore, this is a valid call! +TypeScript は、与えられた引数が有効な`Empty`であるかどうか調べることで、ここでの`fn`の呼び出しが有効なものかどうかを判断します。 +これは、`{ k: 10 }`と`class Empty { }`の _構造_ を調べることで分かります。 +`Empty`にはプロパティがないため、`{ k: 10 }`は`Empty`が持つプロパティを _すべて_ 持っていると考えることができます。 +したがって、これは有効な呼び出しとなるのです! -This may seem surprising, but it's ultimately a very similar relationship to one enforced in nominal OOP languages. -A subclass cannot _remove_ a property of its base class, because doing so would destroy the natural subtype relationship between the derived class and its base. -Structural type systems simply identify this relationship implicitly by describing subtypes in terms of having properties of compatible types. +これは驚くことに思えるかもしれませんが、結果的には名目オブジェクト指向のプログラミング言語で強制されるものと非常によく似ています。 +部分型は基底クラスのプロパティを _削除_ することはできません。というのも、そうしてしまうと派生クラスは基底クラスの部分型であるという当たり前の関係を壊してしまうからです。 +構造的型システムは、互換性のある型のプロパティを持つという観点から部分型を記述することで、この関係を暗黙的に確認しています。 -#### Identical Types +#### 一致する型 -Another frequent source of surprise comes with identical types: +もう一つのよくある驚きの原因は型同士が一致することによるものです: ```ts class Car { drive() { - // hit the gas + // 車を飛ばす } } class Golfer { drive() { - // hit the ball far + // ボールを遠くまで飛ばす } } -// No error? +// エラーにならない? let w: Car = new Golfer(); ``` -Again, this isn't an error because the _structures_ of these classes are the same. -While this may seem like a potential source of confusion, in practice, identical classes that shouldn't be related are not common. +繰り返しになりますが、これらのクラスの _構造体_ は同じなのでエラーになりません。 +混乱のもとになりそうだと思うかもしれませんが、実際には関連するはずのないクラスが一致することは一般的ではありません。 -We'll learn more about how classes relate to each other in the Classes chapter. +クラスがどのように相互に関連しているのかについては、クラスの章で詳しく学びます。 -### Reflection +### リフレクション -OOP programmers are accustomed to being able to query the type of any value, even a generic one: +オブジェクト指向のプログラマは、ジェネリクスであっても任意の値の型を問い合わせることができることに馴染みがあります。 ```csharp // C# @@ -181,11 +181,11 @@ static void LogType() { } ``` -Because TypeScript's type system is fully erased, information about e.g. the instantiation of a generic type parameter is not available at runtime. +TypeScript の型は完全に消去されるので、ジェネリクスの型パラメータのインスタンス化などの情報は実行時には利用できません。 -JavaScript does have some limited primitives like `typeof` and `instanceof`, but remember that these operators are still working on the values as they exist in the type-erased output code. -For example, `typeof (new Car())` will be `"object"`, not `Car` or `"Car"`. +JavaScript には`typeof`と`instanceof`のような限定的なプリミティブがありますが、これらの演算子は型が削除された出力コードに存在する値を扱うことに注意してください。 +例えば、`typeof (new Car())`は、`"object"`となり、`Car`や`"Car"`とはなりません。 --- -This is an overview, from here you should read [through the handbook](/docs/handbook/intro.html) or explore the [Playground examples](/play#show-examples) +本ガイドは概要です。ここから[ハンドブック](/docs/handbook/intro.html)や[Playground 例](/play#show-examples)に進んでみてください。 diff --git a/docs/documentation/ja/get-started/TS for the New Programmer.md b/docs/documentation/ja/get-started/TS for the New Programmer.md index dae4be37..2491bee6 100644 --- a/docs/documentation/ja/get-started/TS for the New Programmer.md +++ b/docs/documentation/ja/get-started/TS for the New Programmer.md @@ -1,65 +1,65 @@ --- -title: TypeScript for the New Programmer -short: TS for the New Programmer +title: 新米プログラマーのための TypeScript +short: 新米プログラマーのための TS layout: docs -permalink: /docs/handbook/typescript-from-scratch.html -oneline: Learn TypeScript from scratch +permalink: /ja/docs/handbook/typescript-from-scratch.html +oneline: ゼロから TypeScript を学ぶ --- -Congratulations on choosing TypeScript as one of your first languages — you're already making good decisions! +初めての言語のひとつとして TypeScript を選んだこと、おめでとうございます -- 良い選択をしましたね! -You've probably already heard that TypeScript is a "flavor" or "variant" of JavaScript. -The relationship between TypeScript (TS) and JavaScript (JS) is rather unique among modern programming languages, so learning more about this relationship will help you understand how TypeScript adds to JavaScript. +おそらく TypeScript が JavaScript"風"だとか"亜種"だとかはすでに聞いたことがあるでしょう。 +TypeScript(TS) と JavaScript(JS) の関係は、モダンなプログラミング言語の中ではとてもユニークなものなので、これらの関係を学ぶことで TypeScript が JavaScript をどのように強力にしたのか理解することができます。 -## What is JavaScript? A Brief History +## JavaScript とは?簡潔な歴史 -JavaScript (also known as ECMAScript) started its life as a simple scripting language for browsers. -At the time it was invented, it was expected to be used for short snippets of code embedded in a web page — writing more than a few dozen lines of code would have been somewhat unusual. -Due to this, early web browsers executed such code pretty slowly. -Over time, though, JS became more and more popular, and web developers started using it to create interactive experiences. +JavaScript(別名 ECMAScript) は、ブラウザ用のシンプルなスクリプト言語として生まれました。 +この言語が発明された当時は、Web ページに埋め込まれた短いコードのスニペットとして使われることが期待されていました - 数十行以上のコードを書くことはややまれだったでしょう。 +そのため、初期の Web ブラウザではそのようなコードの実行はとても遅いものでした。 +しかし、時が経つにつれ、JS の人気はいよいよ増していき、Web 開発者はインタラクティブな体験を作るために使いはじめます。 -Web browser developers responded to this increased JS usage by optimizing their execution engines (dynamic compilation) and extending what could be done with it (adding APIs), which in turn made web developers use it even more. -On modern websites, your browser is frequently running applications that span hundreds of thousands of lines of code. -This is long and gradual growth of "the web", starting as a simple network of static pages, and evolving into a platform for rich _applications_ of all kinds. +Web ブラウザの開発者は、JS の使用量の増大に対して、実行エンジンの最適化(動的コンパイル)や JS でできることの拡張(API の追加)によって対応し、これによって Web 開発者はさらに JS を使うようになりました。 +モダンな Web サイトでは、ブラウザは何十万行にも及ぶコードのアプリケーションを頻繁に実行しています。 +これが、静的なページのシンプルなネットワークとしてはじまり、あらゆる種類のリッチな _アプリケーション_ のためのプラットフォームへと進化していく"Web"の長く緩やかな成長過程です。 -More than this, JS has become popular enough to be used outside the context of browsers, such as implementing JS servers using node.js. -The "run anywhere" nature of JS makes it an attractive choice for cross-platform development. -There are many developers these days that use _only_ JavaScript to program their entire stack! +それ以上に、JS は node.js を使った JS サーバーの実装など、ブラウザのコンテキストの外側でも使えるほど普及してきました。 +"どこでも実行できる"という JS の性質は、クラスプラットフォーム開発にとって魅力的な選択肢です。 +今日では、スタック全体をプログラムするために JavaScript _だけ_ を使う開発者もたくさんいます。 -To summarize, we have a language that was designed for quick uses, and then grew to a full-fledged tool to write applications with millions of lines. -Every language has its own _quirks_ — oddities and surprises, and JavaScript's humble beginning makes it have _many_ of these. Some examples: +要約すると、手早く使用するために設計された言語があり、それが何百万行ものアプリケーションを記述するための本格的なツールとして成長した、ということです。 +どんな言語でも、独自の _癖_ (特異性や意外性) がありますが、JavaScript にはその謙虚なはじまりゆえに、とくに _たくさん_ 癖があります。いくつか例を見てみましょう: -- JavaScript's equality operator (`==`) _coerces_ its arguments, leading to unexpected behavior: +- JavaScript の等価演算子(`==`)は、引数を _型強制_ しますが、これは予期しないふるまいを引き起こします: ```js if ("" == 0) { - // It is! But why?? + // これは等価です! でもなぜ?? } if (1 < x < 3) { - // True for *any* value of x! + // x が "どのような" 値であっても True です! } ``` -- JavaScript also allows accessing properties which aren't present: +- JavaScript では、存在しないプロパティにアクセスすることもできます: ```js const obj = { width: 10, height: 15 }; - // Why is this NaN? Spelling is hard! + // なぜこれが NaN なのか?正しくスペルを打つのが難しい! const area = obj.width * obj.heigth; ``` -Most programming languages would throw an error when these sorts of errors occur, some would do so during compilation — before any code is running. -When writing small programs, such quirks are annoying but manageable; when writing applications with hundreds or thousands of lines of code, these constant surprises are a serious problem. +ほとんどのプログラミング言語は、こういったエラーが起こった時にはエラーをスローしてくれます。コンパイル中、つまりコードの実行前にエラーのスローを行う言語もあります。 +小さなプログラムを書いているときはこういった癖は迷惑ですが、なんとかなります。対して、何百、何千行といったコードのアプリケーションを書いているときは、こうした癖が次々と表出し、深刻な問題となります。 -## TypeScript: A Static Type Checker +## TypeScript: 静的な型チェッカー -We said earlier that some languages wouldn't allow those buggy programs to run at all. -Detecting errors in code without running it is referred to as _static checking_. -Determining what's an error and what's not based on the kinds of values being operated on is known as static _type_ checking. +いくつかの言語ではこういったバグだらけのプログラムを実行することはできないと前述しました。 +コードを実行せずにエラーを検出することを、 _静的チェック_ と言います。 +何がエラーで何がエラーでないのか、操作されている値の種類に基づいて検出することは、静的な _型_ チェックと呼ばれています。 -TypeScript checks a program for errors before execution, and does so based on the _kinds of values_, it's a _static type checker_. -For example, the last example above has an error because of the _type_ of `obj`. -Here's the error TypeScript found: +TypeScript は、実行前にプログラムのエラーがないかチェックしますが、これは _値の種類_ に基づいて行われるので _静的な型チェッカー_ と言えます。 +例えば、前述の最後の例では`obj`の _型_ が原因でエラーが出ています。 +以下は、TypeScript が検出したエラーです: ```ts twoslash // @errors: 2551 @@ -67,60 +67,60 @@ const obj = { width: 10, height: 15 }; const area = obj.width * obj.heigth; ``` -### A Typed Superset of JavaScript +### JavaScript の型付きスーパーセット -How does TypeScript relate to JavaScript, though? +ところで、TypeScript は JavaScript とどんな関係にあるのでしょうか? -#### Syntax +#### 構文 -TypeScript is a language that is a _superset_ of JavaScript: JS syntax is therefore legal TS. -Syntax refers to the way we write text to form a program. -For example, this code has a _syntax_ error because it's missing a `)`: +TypeScript は JavaScript の _スーパーセット_ である言語です。したがって JS の構文は正しい TS です。 +構文とは、プログラムを形成するテキストの書き方のことを言います。 +例えば、以下のコードには`)`がないので _構文_ エラーになります。 ```ts twoslash // @errors: 1005 let a = (4 ``` -TypeScript doesn't consider any JavaScript code to be an error because of its syntax. -This means you can take any working JavaScript code and put it in a TypeScript file without worrying about exactly how it is written. +TypeScript は、どんな JavaScript コードであっても、構文が原因でエラーになるとは考えません。 +つまり、JavaScript がいったいどのように書かれているのかについては気にする必要はなく、動作する JavaScript コードであれば何でも TypeScript のファイルに入れることができるということです。 -#### Types +#### 型 -However, TypeScript is a _typed_ superset, meaning that it adds rules about how different kinds of values can be used. -The earlier error about `obj.heigth` was not a _syntax_ error: it is an error of using some kind of value (a _type_) in an incorrect way. +しかし、TypeScript は _型付き_ のスーパーセットです。つまり、異なる種類の値がどのように使われることができるかといったルールを追加するという言語であるということです。 +前述の`obj.heigth`のエラーは _構文_ のエラーではありません。ある種の値(_型_)を間違った方法で使ったことによるエラーです。 -As another example, this is JavaScript code that you can run in your browser, and it _will_ log a value: +別の例として、以下はブラウザで実行でき、値をログに出力するであろう JavaScript コードです。 ```js console.log(4 / []); ``` -This syntactically-legal program logs `Infinity`. -TypeScript, though, considers division of number by an array to be a nonsensical operation, and will issue an error: +これは構文的に正しいプログラムで、`Infinity`と出力します。 +しかし、TypeScript は配列による数値の除算を意味のない操作だとみなし、エラーを出すでしょう。 ```ts twoslash // @errors: 2363 console.log(4 / []); ``` -It's possible you really _did_ intend to divide a number by an array, perhaps just to see what happens, but most of the time, though, this is a programming mistake. -TypeScript's type checker is designed to allow correct programs through while still catching as many common errors as possible. -(Later, we'll learn about settings you can use to configure how strictly TypeScript checks your code.) +何が起こるのか単に確かめるために、配列で数値を割ろうとした可能性もありますが、たいていの場合はプログラミング上のミスでしょう。 +TypeScript の型チェッカーは、正しいプログラムは通過させ、同時に可能な限り、よくあるエラーをキャッチできるように設計されています。 +(後ほど、TypeScript がコードをチェックする厳しさの度合いを調節する設定について学びます。) -If you move some code from a JavaScript file to a TypeScript file, you might see _type errors_ depending on how the code is written. -These may be legitimate problems with the code, or TypeScript being overly conservative. -Throughout this guide we'll demonstrate how to add various TypeScript syntax to eliminate such errors. +JavaScript ファイルから TypeScript ファイルにコードを移した場合、コードの記述方法によっては _型エラー_ が表示されるかもしれません。 +これらはコードにある理にかなった問題かもしれませんし、TypeScript が過度に保守的になっているのかもしれません。 +本ガイドでは、このようなエラーを排除するための様々な TypeScript 構文を追加する方法について説明します。 -#### Runtime Behavior +#### 実行中の動作 -TypeScript is also a programming language that preserves the _runtime behavior_ of JavaScript. -For example, dividing by zero in JavaScript produces `Infinity` instead of throwing a runtime exception. -As a principle, TypeScript **never** changes the runtime behavior of JavaScript code. +TypeScript は JavaScript の _実行中の動作_ を維持するプログラミング言語でもあります。 +例えば、JavaScript では 0 で除算すると実行時の例外が発生するのではなく、`Infinity`が生成されます。 +原則として、TypeScript は JavaScript コードの実行時の動作を **決して** 変更しません。 -This means that if you move code from JavaScript to TypeScript, it is **guaranteed** to run the same way, even if TypeScript thinks that the code has type errors. +つまり、JavaScript から TypeScript にコードを移行した場合、TypeScript がコードに型エラーを検出したとしても、同じように実行されることが **保証** されています。 -Keeping the same runtime behavior as JavaScript is a foundational promise of TypeScript because it means you can easily transition between the two languages without worrying about subtle differences that might make your program stop working. +JavaScript と同じ実行時の動作を維持することは、TypeScript の基本的な約束です。というのも、これはプログラムが動作しなくなる可能性があるようなささいな違いについて気にすることなく、2 つの言語間を簡単に移行できることを意味するからです。 -#### Erased Types +#### 型の削除 -Roughly speaking, once TypeScript's compiler is done with checking your code, it _erases_ the types to produce the resulting "compiled" code. -This means that once your code is compiled, the resulting plain JS code has no type information. +大ざっぱに言ってしまえば、いったん TypeScript のコンパイラがコードのチェックを終えると、"コンパイルされた"コードを生成するために型を _削除_ します。 +つまり、ひとたびコードがコンパイルされれば、結果として生じる JS コードには型情報が含まれないということです。 -This also means that TypeScript never changes the _behavior_ of your program based on the types it inferred. -The bottom line is that while you might see type errors during compilation, the type system itself has no bearing on how your program works when it runs. +これはまた、TypeScript が推測した型に基づいてプログラムの _動作_ を変更することは決してないということを意味します。 +要するに、コンパイル中に型エラーが表示されるかもしれませんが、型システム自体はプログラムの実行中の動作とは関係がないということです。 -Finally, TypeScript doesn't provide any additional runtime libraries. -Your programs will use the same standard library (or external libraries) as JavaScript programs, so there's no additional TypeScript-specific framework to learn. +そして最後に、TypeScript はランタイムライブラリを追加しません。 +あなたのプログラムは JavaScript プログラムと同じ標準ライブラリ(または外部ライブラリ)を使用するので、学習が必要な TypeScript 特有のフレームワークが追加されるということはありません。 -## Learning JavaScript and TypeScript +## JavaScript と TypeScript の学習 -We frequently see the question "Should I learn JavaScript or TypeScript?". +"JavaScript と TypeScript、どちらを学ぶべきか?"という質問をよく目にします。 -The answer is that you can't learn TypeScript without learning JavaScript! -TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time. +答えとしては、JavaScript を学ばずして TypeScript を学ぶことはできません! +TypeScript は JavaScript と構文および実行中の動作を共有しているので、JavaScript を学ぶことは、同時に TypeScript を学ぶことにもつながります。 -There are many, many resources available for programmers to learn JavaScript; you should _not_ ignore these resources if you're writing TypeScript. -For example, there are about 20 times more StackOverflow questions tagged `javascript` than `typescript`, but _all_ of the `javascript` questions also apply to TypeScript. +プログラマが JavaScript を学ぶための資料はとてもたくさんあります。TypeScript を書いているのであれば、こうした資料は無視できません。 +例えば、StackOverflow には`javascript`のタグが付いた質問は`typescript`の約 20 倍ありますが、`javascript`の質問は _すべて_ TypeScript にも当てはまります。 -If you find yourself searching for something like "how to sort a list in TypeScript", remember: **TypeScript is JavaScript's runtime with a compile-time type checker**. -The way you sort a list in TypeScript is the same way you do so in JavaScript. -If you find a resource that uses TypeScript directly, that's great too, but don't limit yourself to thinking you need TypeScript-specific answers for everyday questions about how to accomplish runtime tasks. +もし"TypeScript でリストをソートする方法"といったものを検索していることに気づいたら、**TypeScript はコンパイル時の型チェッカーを備えた JavaScript のランタイム** であることを思い出してください。 +TypeScript でリストをソートする方法は、JavaScript で行う方法と同じです。 +TypeScript を直接使用している資料を見つけた場合は、それは素晴らしいことですが、実行時のタスクを達成する方法についてのありふれた質問に対して、TypeScript 特有の答えが必要だと、思考を制限しないようにしてください。 --- -From here, we'd recommend learning some of the JavaScript fundamentals (the [JavaScript guide at the Mozilla Web Docs](https://developer.mozilla.org/docs/Web/JavaScript/Guide) is a good starting point.) +ここからは JavaScript の基礎を学ぶことをおすすめします。([Mozilla Web Docs の JavaScript ガイド](https://developer.mozilla.org/docs/Web/JavaScript/Guide)は良いスタート地点です。) -Once you're feeling comfortable, you can come back to read [TypeScript for JavaScript Programmers](/docs/handbook/typescript-in-5-minutes.html), then start on [the handbook](/docs/handbook/intro.html) or explore the [Playground examples](/play#show-examples). +慣れてきたら、[JavaScript プログラマのための TypeScript](/docs/handbook/typescript-in-5-minutes.html)や、その後に[ハンドブック](/docs/handbook/intro.html)あるいは[Playground 例](/play#show-examples)を読んでみてください。