From ee6289abd3292e605e42b553a2ad351ee8f98061 Mon Sep 17 00:00:00 2001 From: Masato Urai Date: Tue, 2 Feb 2021 03:14:24 +0900 Subject: [PATCH 1/4] copy en files --- .../ja/tutorials/Babel with TypeScript.md | 49 ++ .../ja/tutorials/DOM Manipulation.md | 201 ++++++++ .../ja/tutorials/Migrating from JavaScript.md | 442 ++++++++++++++++++ docs/documentation/ja/tutorials/React.md | 26 ++ .../TypeScript Tooling in 5 minutes.md | 187 ++++++++ 5 files changed, 905 insertions(+) create mode 100644 docs/documentation/ja/tutorials/Babel with TypeScript.md create mode 100755 docs/documentation/ja/tutorials/DOM Manipulation.md create mode 100644 docs/documentation/ja/tutorials/Migrating from JavaScript.md create mode 100644 docs/documentation/ja/tutorials/React.md create mode 100644 docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md diff --git a/docs/documentation/ja/tutorials/Babel with TypeScript.md b/docs/documentation/ja/tutorials/Babel with TypeScript.md new file mode 100644 index 00000000..a898289a --- /dev/null +++ b/docs/documentation/ja/tutorials/Babel with TypeScript.md @@ -0,0 +1,49 @@ +--- +title: Using Babel with TypeScript +layout: docs +permalink: /docs/handbook/babel-with-typescript.html +oneline: How to create a hybrid Babel + TypeScript project +translatable: true +--- + +## Babel vs `tsc` for TypeScript + +When making a modern JavaScript project, you might ask yourself what is the right way to convert files from TypeScript to JavaScript? + +A lot of the time the answer is _"it depends"_, or _"someone may have decided for you"_ depending on the project. If you are building your project with an existing framework like [tsdx](https://tsdx.io), [Angular](https://angular.io/), [NestJS](https://nestjs.com/) or any framework mentioned in the [Getting Started](/docs/home) then this decision is handled for you. + +However, a useful heuristic could be: + +- Is your build output mostly the same as your source input files? Use `tsc` +- Do you need a build pipeline with multiple potential outputs? Use `babel` for transpiling and `tsc` for type checking + +## Babel for transpiling, `tsc` for types + +This is a common pattern for projects with existing build infrastructure which may have been ported from a JavaScript codebase to TypeScript. + +This technique is a hybrid approach, using Babel's [preset-typescript](https://babeljs.io/docs/en/babel-preset-typescript) to generate your JS files, and then using TypeScript to do type checking and `.d.ts` file generation. + +By using babel's support for TypeScript, you get the ability to work with existing build pipelines and are more likely to have a faster JS emit time because Babel does not type check your code. + +#### Type Checking and d.ts file generation + +The downside to using babel is that you don't get type checking during the transition from TS to JS. This can mean that type errors which you miss in your editor could sneak through into production code. + +In addition to that, Babel cannot create `.d.ts` files for your TypeScript which can make it harder to work with your project if it is a library. + +To fix these issues, you would probably want to set up a command to type check your project using TSC. This likely means duplicating some of your babel config into a corresponding [`tsconfig.json`](/tsconfig) and ensuring these flags are enabled: + +```json tsconfig +"compilerOptions": { + // Ensure that .d.ts files are created by tsc, but not .js files + "declaration": true, + "emitDeclarationOnly": true, + // Ensure that Babel can safely transpile files in the TypeScript project + "isolatedModules": true +} +``` + +For more information on these flags: + +- [`isolatedModules`](/tsconfig#isolatedModules) +- [`declaration`](/tsconfig#declaration), [`emitDeclarationOnly`](/tsconfig#emitDeclarationOnly) diff --git a/docs/documentation/ja/tutorials/DOM Manipulation.md b/docs/documentation/ja/tutorials/DOM Manipulation.md new file mode 100755 index 00000000..9344bb0b --- /dev/null +++ b/docs/documentation/ja/tutorials/DOM Manipulation.md @@ -0,0 +1,201 @@ +--- +title: DOM Manipulation +layout: docs +permalink: /docs/handbook/dom-manipulation.html +oneline: Using the DOM with TypeScript +translatable: true +--- + +## DOM Manipulation + +### _An exploration into the `HTMLElement` type_ + +In the 20+ years since its standardization, JavaScript has come a very long way. While in 2020, JavaScript can be used on servers, in data science, and even on IoT devices, it is important to remember its most popular use case: web browsers. + +Websites are made up of HTML and/or XML documents. These documents are static, they do not change. The *Document Object Model (DOM)* is a programming interface implemented by browsers in order to make static websites functional. The DOM API can be used to change the document structure, style, and content. The API is so powerful that countless frontend frameworks (jQuery, React, Angular, etc.) have been developed around it in order to make dynamic websites even easier to develop. + +TypeScript is a typed superset of JavaScript, and it ships type definitions for the DOM API. These definitions are readily available in any default TypeScript project. Of the 20,000+ lines of definitions in _lib.dom.d.ts_, one stands out among the rest: `HTMLElement` . This type is the backbone for DOM manipulation with TypeScript. + +> You can explore the source code for the [DOM type definitions](https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts) + +## Basic Example + +Given a simplified _index.html_ file: + + + + TypeScript Dom Manipulation + +
+ + + + + +Lets explore a TypeScript script that adds a `

Hello, World

` element to the `#app` element. + +```ts +// 1. Select the div element using the id property +const app = document.getElementById("app"); + +// 2. Create a new

element programmatically +const p = document.createElement("p"); + +// 3. Add the text content +p.textContent = "Hello, World!"; + +// 4. Append the p element to the div element +app?.appendChild(p); +``` + +After compiling and running the _index.html_ page, the resulting HTML will be: + +```html +
+

Hello, World!

+
+``` + +## The `Document` Interface + +The first line of the TypeScript code uses a global variable `document`. Inspecting the variable shows it is defined by the `Document` interface from the _lib.dom.d.ts_ file. The code snippet contains calls to two methods, `getElementById` and `createElement`. + +### `Document.getElementById` + +The definition for this method is as follows: + +```ts +getElementById(elementId: string): HTMLElement | null; +``` + +Pass it an element id string and it will return either `HTMLElement` or `null` . This method introduces one of the most important types, `HTMLElement`. It serves as the base interface for every other element interface. For example, the `p` variable in the code example is of type `HTMLParagraphElement`. Also take note that this method can return `null`. This is because the method can't be certain pre-runtime if it will be able to actually find the specified element or not. In the last line of the code snippet, the new _optional chaining_ operator is used in order to call `appendChild`. + +### `Document.createElement` + +The definition for this method is (I have omitted the _deprecated_ definition): + +```ts +createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; +createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; +``` + +This is an overloaded function definition. The second overload is simplest and works a lot like the `getElementById` method does. Pass it any `string` and it will return a standard HTMLElement. This definition is what enables developers to create unique HTML element tags. + +For example `document.createElement('xyz')` returns a `` element, clearly not an element that is specified by the HTML specification. + +> For those interested, you can interact with custom tag elements using the `document.getElementsByTagName` + +For the first definition of `createElement`, it is using some advanced generic patterns. It is best understood broken down into chunks, starting with the generic expression: ``. This expression defines a generic parameter `K` that is _constrained_ to the keys of the interface `HTMLElementTagNameMap`. The map interface contains every specified HTML tag name and its corresponding type interface. For example here are the first 5 mapped values: + +```ts +interface HTMLElementTagNameMap { + "a": HTMLAnchorElement; + "abbr": HTMLElement; + "address": HTMLElement; + "applet": HTMLAppletElement; + "area": HTMLAreaElement; + ... +} +``` + +Some elements do not exhibit unique properties and so they just return `HTMLElement`, but other types do have unique properties and methods so they return their specific interface (which will extend from or implement `HTMLElement`). + +Now, for the remainder of the `createElement` definition: `(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]`. The first argument `tagName` is defined as the generic parameter `K` . The TypeScript interpreter is smart enough to _infer_ the generic parameter from this argument. This means that the developer does not actually have to specify the generic parameter when using the method; whatever value is passed to the `tagName` argument will be inferred as `K` and thus can be used throughout the remainder of the definition. Which is exactly what happens; the return value `HTMLElementTagNameMap[K]` takes the `tagName` argument and uses it to return the corresponding type. This definition is how the `p` variable from the code snippet gets a type of `HTMLParagraphElement`. And if the code was `document.createElement('a')`, then it would be an element of type `HTMLAnchorElement`. + +## The `Node` interface + +The `document.getElementById` function returns an `HTMLElement`. `HTMLElement` interface extends the `Element` interface which extends the `Node` interface. This prototypal extension allows for all `HTMLElements` to utilize a subset of standard methods. In the code snippet, we use a property defined on the `Node` interface to append the new `p` element to the website. + +### `Node.appendChild` + +The last line of the code snippet is `app?.appendChild(p)`. The previous, `document.getElementById` , section detailed that the _optional chaining_ operator is used here because `app` can potentially be null at runtime. The `appendChild` method is defined by: + +```ts +appendChild(newChild: T): T; +``` + +This method works similarly to the `createElement` method as the generic parameter `T` is inferred from the `newChild` argument. `T` is _constrained_ to another base interface `Node`. + +## Difference between `children` and `childNodes` + +Previously, this document details the `HTMLElement` interface extends from `Element` which extends from `Node`. In the DOM API there is a concept of _children_ elements. For example in the following HTML, the `p` tags are children of the `div` element + +```tsx +
+

Hello, World

+

TypeScript!

+
; + +const div = document.getElementsByTagName("div")[0]; + +div.children; +// HTMLCollection(2) [p, p] + +div.childNodes; +// NodeList(2) [p, p] +``` + +After capturing the `div` element, the `children` prop will return a `HTMLCollection` list containing the `HTMLParagraphElements`. The `childNodes` property will return a similar `NodeList` list of nodes. Each `p` tag will still be of type `HTMLParagraphElements`, but the `NodeList` can contain additional _HTML nodes_ that the `HTMLCollection` list cannot. + +Modify the html by removing one of the `p` tags, but keep the text. + +```tsx +
+

Hello, World

+ TypeScript! +
; + +const div = document.getElementsByTagName("div")[0]; + +div.children; +// HTMLCollection(1) [p] + +div.childNodes; +// NodeList(2) [p, text] +``` + +See how both lists change. `children` now only contains the `

Hello, World

` element, and the `childNodes` contains a `text` node rather than two `p` nodes. The `text` part of the `NodeList` is the literal `Node` containing the text `TypeScript!`. The `children` list does not contain this `Node` because it is not considered an `HTMLElement`. + +## The `querySelector` and `querySelectorAll` methods + +Both of these methods are great tools for getting lists of dom elements that fit a more unique set of constraints. They are defined in _lib.dom.d.ts_ as: + +```ts +/** + * Returns the first element that is a descendant of node that matches selectors. + */ +querySelector(selectors: K): HTMLElementTagNameMap[K] | null; +querySelector(selectors: K): SVGElementTagNameMap[K] | null; +querySelector(selectors: string): E | null; + +/** + * Returns all element descendants of node that match selectors. + */ +querySelectorAll(selectors: K): NodeListOf; +querySelectorAll(selectors: K): NodeListOf; +querySelectorAll(selectors: string): NodeListOf; +``` + +The `querySelectorAll` definition is similar to `getElementsByTagName`, except it returns a new type: `NodeListOf`. This return type is essentially a custom implementation of the standard JavaScript list element. Arguably, replacing `NodeListOf` with `E[]` would result in a very similar user experience. `NodeListOf` only implements the following properties and methods: `length` , `item(index)`, `forEach((value, key, parent) => void)` , and numeric indexing. Additionally, this method returns a list of _elements_, not _nodes_, which is what `NodeList` was returning from the `.childNodes` method. While this may appear as a discrepancy, take note that interface `Element` extends from `Node`. + +To see these methods in action modify the existing code to: + +```tsx +
    +
  • First :)
  • +
  • Second!
  • +
  • Third times a charm.
  • +
; + +const first = document.querySelector("li"); // returns the first li element +const all = document.querySelectorAll("li"); // returns the list of all li elements +``` + +## Interested in learning more? + +The best part about the _lib.dom.d.ts_ type definitions is that they are reflective of the types annotated in the Mozilla Developer Network (MDN) documentation site. For example, the `HTMLElement` interface is documented by this [HTMLElement page](https://developer.mozilla.org/docs/Web/API/HTMLElement) on MDN. These pages list all available properties, methods, and sometimes even examples. Another great aspect of the pages is that they provide links to the corresponding standard documents. Here is the link to the [W3C Recommendation for HTMLElement](https://www.w3.org/TR/html52/dom.html#htmlelement). + +Sources: + +- [ECMA-262 Standard](http://www.ecma-international.org/ecma-262/10.0/index.html) +- [Introduction to the DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) diff --git a/docs/documentation/ja/tutorials/Migrating from JavaScript.md b/docs/documentation/ja/tutorials/Migrating from JavaScript.md new file mode 100644 index 00000000..be31153a --- /dev/null +++ b/docs/documentation/ja/tutorials/Migrating from JavaScript.md @@ -0,0 +1,442 @@ +--- +title: Migrating from JavaScript +layout: docs +permalink: /docs/handbook/migrating-from-javascript.html +oneline: How to migrate from JavaScript to TypeScript +--- + +TypeScript doesn't exist in a vacuum. +It was built with the JavaScript ecosystem in mind, and a lot of JavaScript exists today. +Converting a JavaScript codebase over to TypeScript is, while somewhat tedious, usually not challenging. +In this tutorial, we're going to look at how you might start out. +We assume you've read enough of the handbook to write new TypeScript code. + +If you're looking to convert a React project, we recommend looking at the [React Conversion Guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide) first. + +## Setting up your Directories + +If you're writing in plain JavaScript, it's likely that you're running your JavaScript directly, +where your `.js` files are in a `src`, `lib`, or `dist` directory, and then ran as desired. + +If that's the case, the files that you've written are going to be used as inputs to TypeScript, and you'll run the outputs it produces. +During our JS to TS migration, we'll need to separate our input files to prevent TypeScript from overwriting them. +If your output files need to reside in a specific directory, then that will be your output directory. + +You might also be running some intermediate steps on your JavaScript, such as bundling or using another transpiler like Babel. +In this case, you might already have a folder structure like this set up. + +From this point on, we're going to assume that your directory is set up something like this: + +``` +projectRoot +├── src +│ ├── file1.js +│ └── file2.js +├── built +└── tsconfig.json +``` + +If you have a `tests` folder outside of your `src` directory, you might have one `tsconfig.json` in `src`, and one in `tests` as well. + +## Writing a Configuration File + +TypeScript uses a file called `tsconfig.json` for managing your project's options, such as which files you want to include, and what sorts of checking you want to perform. +Let's create a bare-bones one for our project: + +```json +{ + "compilerOptions": { + "outDir": "./built", + "allowJs": true, + "target": "es5" + }, + "include": ["./src/**/*"] +} +``` + +Here we're specifying a few things to TypeScript: + +1. Read in any files it understands in the `src` directory (with `include`). +2. Accept JavaScript files as inputs (with `allowJs`). +3. Emit all of the output files in `built` (with `outDir`). +4. Translate newer JavaScript constructs down to an older version like ECMAScript 5 (using `target`). + +At this point, if you try running `tsc` at the root of your project, you should see output files in the `built` directory. +The layout of files in `built` should look identical to the layout of `src`. +You should now have TypeScript working with your project. + +## Early Benefits + +Even at this point you can get some great benefits from TypeScript understanding your project. +If you open up an editor like [VS Code](https://code.visualstudio.com) or [Visual Studio](https://visualstudio.com), you'll see that you can often get some tooling support like completion. +You can also catch certain bugs with options like: + +- `noImplicitReturns` which prevents you from forgetting to return at the end of a function. +- `noFallthroughCasesInSwitch` which is helpful if you never want to forget a `break` statement between `case`s in a `switch` block. + +TypeScript will also warn about unreachable code and labels, which you can disable with `allowUnreachableCode` and `allowUnusedLabels` respectively. + +## Integrating with Build Tools + +You might have some more build steps in your pipeline. +Perhaps you concatenate something to each of your files. +Each build tool is different, but we'll do our best to cover the gist of things. + +## Gulp + +If you're using Gulp in some fashion, we have a tutorial on [using Gulp](/docs/handbook/gulp.html) with TypeScript, and integrating with common build tools like Browserify, Babelify, and Uglify. +You can read more there. + +## Webpack + +Webpack integration is pretty simple. +You can use `ts-loader`, a TypeScript loader, combined with `source-map-loader` for easier debugging. +Simply run + +```shell +npm install ts-loader source-map-loader +``` + +and merge in options from the following into your `webpack.config.js` file: + +```js +module.exports = { + entry: "./src/index.ts", + output: { + filename: "./dist/bundle.js", + }, + + // Enable sourcemaps for debugging webpack's output. + devtool: "source-map", + + resolve: { + // Add '.ts' and '.tsx' as resolvable extensions. + extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"], + }, + + module: { + rules: [ + // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. + { test: /\.tsx?$/, loader: "ts-loader" }, + + // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. + { test: /\.js$/, loader: "source-map-loader" }, + ], + }, + + // Other options... +}; +``` + +It's important to note that ts-loader will need to run before any other loader that deals with `.js` files. + +The same goes for [awesome-typescript-loader](https://github.com/TypeStrong/ts-loader), another TypeScript loader for Webpack. +You can read more about the differences between the two [here](https://github.com/s-panferov/awesome-typescript-loader#differences-between-ts-loader). + +You can see an example of using Webpack in our [tutorial on React and Webpack](/docs/handbook/react-&-webpack.html). + +## Moving to TypeScript Files + +At this point, you're probably ready to start using TypeScript files. +The first step is to rename one of your `.js` files to `.ts`. +If your file uses JSX, you'll need to rename it to `.tsx`. + +Finished with that step? +Great! +You've successfully migrated a file from JavaScript to TypeScript! + +Of course, that might not feel right. +If you open that file in an editor with TypeScript support (or if you run `tsc --pretty`), you might see red squiggles on certain lines. +You should think of these the same way you'd think of red squiggles in an editor like Microsoft Word. +TypeScript will still translate your code, just like Word will still let you print your documents. + +If that sounds too lax for you, you can tighten that behavior up. +If, for instance, you _don't_ want TypeScript to compile to JavaScript in the face of errors, you can use the `noEmitOnError` option. +In that sense, TypeScript has a dial on its strictness, and you can turn that knob up as high as you want. + +If you plan on using the stricter settings that are available, it's best to turn them on now (see [Getting Stricter Checks](#getting-stricter-checks) below). +For instance, if you never want TypeScript to silently infer `any` for a type without you explicitly saying so, you can use `noImplicitAny` before you start modifying your files. +While it might feel somewhat overwhelming, the long-term gains become apparent much more quickly. + +## Weeding out Errors + +Like we mentioned, it's not unexpected to get error messages after conversion. +The important thing is to actually go one by one through these and decide how to deal with the errors. +Often these will be legitimate bugs, but sometimes you'll have to explain what you're trying to do a little better to TypeScript. + +### Importing from Modules + +You might start out getting a bunch of errors like `Cannot find name 'require'.`, and `Cannot find name 'define'.`. +In these cases, it's likely that you're using modules. +While you can just convince TypeScript that these exist by writing out + +```ts +// For Node/CommonJS +declare function require(path: string): any; +``` + +or + +```ts +// For RequireJS/AMD +declare function define(...args: any[]): any; +``` + +it's better to get rid of those calls and use TypeScript syntax for imports. + +First, you'll need to enable some module system by setting TypeScript's `module` flag. +Valid options are `commonjs`, `amd`, `system`, and `umd`. + +If you had the following Node/CommonJS code: + +```js +var foo = require("foo"); + +foo.doStuff(); +``` + +or the following RequireJS/AMD code: + +```js +define(["foo"], function (foo) { + foo.doStuff(); +}); +``` + +then you would write the following TypeScript code: + +```ts +import foo = require("foo"); + +foo.doStuff(); +``` + +### Getting Declaration Files + +If you started converting over to TypeScript imports, you'll probably run into errors like `Cannot find module 'foo'.`. +The issue here is that you likely don't have _declaration files_ to describe your library. +Luckily this is pretty easy. +If TypeScript complains about a package like `lodash`, you can just write + +```shell +npm install -S @types/lodash +``` + +If you're using a module option other than `commonjs`, you'll need to set your `moduleResolution` option to `node`. + +After that, you'll be able to import lodash with no issues, and get accurate completions. + +### Exporting from Modules + +Typically, exporting from a module involves adding properties to a value like `exports` or `module.exports`. +TypeScript allows you to use top-level export statements. +For instance, if you exported a function like so: + +```js +module.exports.feedPets = function (pets) { + // ... +}; +``` + +you could write that out as the following: + +```ts +export function feedPets(pets) { + // ... +} +``` + +Sometimes you'll entirely overwrite the exports object. +This is a common pattern people use to make their modules immediately callable like in this snippet: + +```js +var express = require("express"); +var app = express(); +``` + +You might have previously written that like so: + +```js +function foo() { + // ... +} +module.exports = foo; +``` + +In TypeScript, you can model this with the `export =` construct. + +```ts +function foo() { + // ... +} +export = foo; +``` + +### Too many/too few arguments + +You'll sometimes find yourself calling a function with too many/few arguments. +Typically, this is a bug, but in some cases, you might have declared a function that uses the `arguments` object instead of writing out any parameters: + +```js +function myCoolFunction() { + if (arguments.length == 2 && !Array.isArray(arguments[1])) { + var f = arguments[0]; + var arr = arguments[1]; + // ... + } + // ... +} + +myCoolFunction( + function (x) { + console.log(x); + }, + [1, 2, 3, 4] +); +myCoolFunction( + function (x) { + console.log(x); + }, + 1, + 2, + 3, + 4 +); +``` + +In this case, we need to use TypeScript to tell any of our callers about the ways `myCoolFunction` can be called using function overloads. + +```ts +function myCoolFunction(f: (x: number) => void, nums: number[]): void; +function myCoolFunction(f: (x: number) => void, ...nums: number[]): void; +function myCoolFunction() { + if (arguments.length == 2 && !Array.isArray(arguments[1])) { + var f = arguments[0]; + var arr = arguments[1]; + // ... + } + // ... +} +``` + +We added two overload signatures to `myCoolFunction`. +The first checks states that `myCoolFunction` takes a function (which takes a `number`), and then a list of `number`s. +The second one says that it will take a function as well, and then uses a rest parameter (`...nums`) to state that any number of arguments after that need to be `number`s. + +### Sequentially Added Properties + +Some people find it more aesthetically pleasing to create an object and add properties immediately after like so: + +```js +var options = {}; +options.color = "red"; +options.volume = 11; +``` + +TypeScript will say that you can't assign to `color` and `volume` because it first figured out the type of `options` as `{}` which doesn't have any properties. +If you instead moved the declarations into the object literal themselves, you'd get no errors: + +```ts +let options = { + color: "red", + volume: 11, +}; +``` + +You could also define the type of `options` and add a type assertion on the object literal. + +```ts +interface Options { + color: string; + volume: number; +} + +let options = {} as Options; +options.color = "red"; +options.volume = 11; +``` + +Alternatively, you can just say `options` has the type `any` which is the easiest thing to do, but which will benefit you the least. + +### `any`, `Object`, and `{}` + +You might be tempted to use `Object` or `{}` to say that a value can have any property on it because `Object` is, for most purposes, the most general type. +However **`any` is actually the type you want to use** in those situations, since it's the most _flexible_ type. + +For instance, if you have something that's typed as `Object` you won't be able to call methods like `toLowerCase()` on it. +Being more general usually means you can do less with a type, but `any` is special in that it is the most general type while still allowing you to do anything with it. +That means you can call it, construct it, access properties on it, etc. +Keep in mind though, whenever you use `any`, you lose out on most of the error checking and editor support that TypeScript gives you. + +If a decision ever comes down to `Object` and `{}`, you should prefer `{}`. +While they are mostly the same, technically `{}` is a more general type than `Object` in certain esoteric cases. + +## Getting Stricter Checks + +TypeScript comes with certain checks to give you more safety and analysis of your program. +Once you've converted your codebase to TypeScript, you can start enabling these checks for greater safety. + +### No Implicit `any` + +There are certain cases where TypeScript can't figure out what certain types should be. +To be as lenient as possible, it will decide to use the type `any` in its place. +While this is great for migration, using `any` means that you're not getting any type safety, and you won't get the same tooling support you'd get elsewhere. +You can tell TypeScript to flag these locations down and give an error with the `noImplicitAny` option. + +### Strict `null` & `undefined` Checks + +By default, TypeScript assumes that `null` and `undefined` are in the domain of every type. +That means anything declared with the type `number` could be `null` or `undefined`. +Since `null` and `undefined` are such a frequent source of bugs in JavaScript and TypeScript, TypeScript has the `strictNullChecks` option to spare you the stress of worrying about these issues. + +When `strictNullChecks` is enabled, `null` and `undefined` get their own types called `null` and `undefined` respectively. +Whenever anything is _possibly_ `null`, you can use a union type with the original type. +So for instance, if something could be a `number` or `null`, you'd write the type out as `number | null`. + +If you ever have a value that TypeScript thinks is possibly `null`/`undefined`, but you know better, you can use the postfix `!` operator to tell it otherwise. + +```ts +declare var foo: string[] | null; + +foo.length; // error - 'foo' is possibly 'null' + +foo!.length; // okay - 'foo!' just has type 'string[]' +``` + +As a heads up, when using `strictNullChecks`, your dependencies may need to be updated to use `strictNullChecks` as well. + +### No Implicit `any` for `this` + +When you use the `this` keyword outside of classes, it has the type `any` by default. +For instance, imagine a `Point` class, and imagine a function that we wish to add as a method: + +```ts +class Point { + constructor(public x, public y) {} + getDistance(p: Point) { + let dx = p.x - this.x; + let dy = p.y - this.y; + return Math.sqrt(dx ** 2 + dy ** 2); + } +} +// ... + +// Reopen the interface. +interface Point { + distanceFromOrigin(): number; +} +Point.prototype.distanceFromOrigin = function () { + return this.getDistance({ x: 0, y: 0 }); +}; +``` + +This has the same problems we mentioned above - we could easily have misspelled `getDistance` and not gotten an error. +For this reason, TypeScript has the `noImplicitThis` option. +When that option is set, TypeScript will issue an error when `this` is used without an explicit (or inferred) type. +The fix is to use a `this`-parameter to give an explicit type in the interface or in the function itself: + +```ts +Point.prototype.distanceFromOrigin = function (this: Point) { + return this.getDistance({ x: 0, y: 0 }); +}; +``` diff --git a/docs/documentation/ja/tutorials/React.md b/docs/documentation/ja/tutorials/React.md new file mode 100644 index 00000000..773ea021 --- /dev/null +++ b/docs/documentation/ja/tutorials/React.md @@ -0,0 +1,26 @@ +--- +title: React +layout: docs +permalink: /docs/handbook/react.html +oneline: Links to learn about TypeScript and React +translatable: true +--- + +TypeScript supports [JSX](/docs/handbook/jsx.html) and can correctly model the patterns used in React codebases like `useState`. + +### Getting Set Up With a React Project + +Today there are many frameworks which support TypeScript out of the box: + +- [Create React App](https://create-react-app.dev) - [TS docs](https://create-react-app.dev/docs/adding-typescript/) +- [Next.js](https://nextjs.org) - [TS docs](https://nextjs.org/learn/excel/typescript) +- [Gatsby](https://www.gatsbyjs.org) - [TS Docs](https://www.gatsbyjs.org/docs/typescript/) + +All of these are great starting points. We [use Gatsby](https://www.gatsbyjs.org/blog/2020-01-23-why-typescript-chose-gatsby/#reach-skip-nav) with TypeScript for [this website](https://github.com/microsoft/TypeScript-Website/), so that can also be a useful reference implementation. + +### Documentation + +Here are some of the best places to find up-to-date information on React and TypeScript: + +- [React TypeScript Cheatsheets](https://react-typescript-cheatsheet.netlify.app) +- [React & Redux in TypeScript](https://github.com/piotrwitek/react-redux-typescript-guide#react--redux-in-typescript---complete-guide) diff --git a/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md b/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md new file mode 100644 index 00000000..b056c7f3 --- /dev/null +++ b/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md @@ -0,0 +1,187 @@ +--- +title: TypeScript Tooling in 5 minutes +layout: docs +permalink: /docs/handbook/typescript-tooling-in-5-minutes.html +oneline: A tutorial to understand how to create a small website with TypeScript +translatable: true +--- + +Let's get started by building a simple web application with TypeScript. + +## Installing TypeScript + +There are two main ways to get the TypeScript available for your project: + +- Via npm (the Node.js package manager) +- By installing TypeScript's Visual Studio plugins + +Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. +If you didn't install TypeScript with Visual Studio, you can still [download it](/download). + +For npm users: + +```shell +> npm install -g typescript +``` + +## Building your first TypeScript file + +In your editor, type the following JavaScript code in `greeter.ts`: + +```ts twoslash +// @noImplicitAny: false +function greeter(person) { + return "Hello, " + person; +} + +let user = "Jane User"; + +document.body.textContent = greeter(user); +``` + +## Compiling your code + +We used a `.ts` extension, but this code is just JavaScript. +You could have copy/pasted this straight out of an existing JavaScript app. + +At the command line, run the TypeScript compiler: + +```shell +tsc greeter.ts +``` + +The result will be a file `greeter.js` which contains the same JavaScript that you fed in. +We're up and running using TypeScript in our JavaScript app! + +Now we can start taking advantage of some of the new tools TypeScript offers. +Add a `: string` type annotation to the 'person' function argument as shown here: + +```ts twoslash +function greeter(person: string) { + return "Hello, " + person; +} + +let user = "Jane User"; + +document.body.textContent = greeter(user); +``` + +## Type annotations + +Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. +In this case, we intend the greeter function to be called with a single string parameter. +We can try changing the call greeter to pass an array instead: + +```ts twoslash +// @errors: 2345 +function greeter(person: string) { + return "Hello, " + person; +} + +let user = [0, 1, 2]; + +document.body.textContent = greeter(user); +``` + +Re-compiling, you'll now see an error: + +```shell +error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'. +``` + +Similarly, try removing all the arguments to the greeter call. +TypeScript will let you know that you have called this function with an unexpected number of parameters. +In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide. + +Notice that although there were errors, the `greeter.js` file is still created. +You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected. + +## Interfaces + +Let's develop our sample further. Here we use an interface that describes objects that have a firstName and lastName field. +In TypeScript, two types are compatible if their internal structure is compatible. +This allows us to implement an interface just by having the shape the interface requires, without an explicit `implements` clause. + +```ts twoslash +interface Person { + firstName: string; + lastName: string; +} + +function greeter(person: Person) { + return "Hello, " + person.firstName + " " + person.lastName; +} + +let user = { firstName: "Jane", lastName: "User" }; + +document.body.textContent = greeter(user); +``` + +## Classes + +Finally, let's extend the example one last time with classes. +TypeScript supports new features in JavaScript, like support for class-based object-oriented programming. + +Here we're going to create a `Student` class with a constructor and a few public fields. +Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction. + +Also of note, the use of `public` on arguments to the constructor is a shorthand that allows us to automatically create properties with that name. + +```ts twoslash +class Student { + fullName: string; + constructor( + public firstName: string, + public middleInitial: string, + public lastName: string + ) { + this.fullName = firstName + " " + middleInitial + " " + lastName; + } +} + +interface Person { + firstName: string; + lastName: string; +} + +function greeter(person: Person) { + return "Hello, " + person.firstName + " " + person.lastName; +} + +let user = new Student("Jane", "M.", "User"); + +document.body.textContent = greeter(user); +``` + +Re-run `tsc greeter.ts` and you'll see the generated JavaScript is the same as the earlier code. +Classes in TypeScript are just a shorthand for the same prototype-based OO that is frequently used in JavaScript. + +## Running your TypeScript web app + +Now type the following in `greeter.html`: + +```html + + + + TypeScript Greeter + + + + + +``` + +Open `greeter.html` in the browser to run your first simple TypeScript web application! + +Optional: Open `greeter.ts` in Visual Studio, or copy the code into the TypeScript playground. +You can hover over identifiers to see their types. +Notice that in some cases these types are inferred automatically for you. +Re-type the last line, and see completion lists and parameter help based on the types of the DOM elements. +Put your cursor on the reference to the greeter function, and hit F12 to go to its definition. +Notice, too, that you can right-click on a symbol and use refactoring to rename it. + +The type information provided works together with the tools to work with JavaScript at application scale. +For more examples of what's possible in TypeScript, see the Samples section of the website. + +![Visual Studio picture](/images/docs/greet_person.png) From 22bc95d7c234a5515af87aab9b952f5152cd370b Mon Sep 17 00:00:00 2001 From: Masato Urai Date: Tue, 2 Feb 2021 03:17:58 +0900 Subject: [PATCH 2/4] translate files into ja --- .../ja/tutorials/Babel with TypeScript.md | 42 +-- .../ja/tutorials/DOM Manipulation.md | 98 +++--- .../ja/tutorials/Migrating from JavaScript.md | 310 +++++++++--------- docs/documentation/ja/tutorials/React.md | 16 +- .../TypeScript Tooling in 5 minutes.md | 108 +++--- 5 files changed, 287 insertions(+), 287 deletions(-) diff --git a/docs/documentation/ja/tutorials/Babel with TypeScript.md b/docs/documentation/ja/tutorials/Babel with TypeScript.md index a898289a..cdda48b5 100644 --- a/docs/documentation/ja/tutorials/Babel with TypeScript.md +++ b/docs/documentation/ja/tutorials/Babel with TypeScript.md @@ -1,49 +1,49 @@ --- -title: Using Babel with TypeScript +title: TypeScriptでBabelを使用する layout: docs -permalink: /docs/handbook/babel-with-typescript.html -oneline: How to create a hybrid Babel + TypeScript project +permalink: /ja/docs/handbook/babel-with-typescript.html +oneline: BabelとTypeScriptを組み合わせたプロジェクトの作成方法 translatable: true --- -## Babel vs `tsc` for TypeScript +## BabelとTypeScriptの`tsc`の比較 -When making a modern JavaScript project, you might ask yourself what is the right way to convert files from TypeScript to JavaScript? +モダンなJavaScriptプロジェクトを作る際、TypeScriptからJavaScriptにファイルをトランスパイルするにはどのような方法が正しいのでしょうか? -A lot of the time the answer is _"it depends"_, or _"someone may have decided for you"_ depending on the project. If you are building your project with an existing framework like [tsdx](https://tsdx.io), [Angular](https://angular.io/), [NestJS](https://nestjs.com/) or any framework mentioned in the [Getting Started](/docs/home) then this decision is handled for you. +その答えは、プロジェクトによって _"状況次第"_ だったり、 _"誰かが決めてくれたもの"_ であることが多いです。[tsdx](https://tsdx.io)、[Angular](https://angular.io/)、[NestJS](https://nestjs.com/)といった既存のフレームワークや、あるいは[Getting Started](/docs/home)で紹介したようなフレームワークを使ってプロジェクトを構築しているのならば、あなたに代わってこの決定を行ってくれます。 -However, a useful heuristic could be: +一方で、有用な経験則としては次のようなものがあります: -- Is your build output mostly the same as your source input files? Use `tsc` -- Do you need a build pipeline with multiple potential outputs? Use `babel` for transpiling and `tsc` for type checking +- ビルド出力はソースの入力ファイルとほとんど同じですか?では、`tsc`を使いましょう +- 出力が複数になる可能性があるビルドパイプラインが必要ですか?では、トランスパイルには`babel`を、型チェックには`tsc`を使いましょう -## Babel for transpiling, `tsc` for types +## トランスパイルのためのBabel、型のための`tsc` -This is a common pattern for projects with existing build infrastructure which may have been ported from a JavaScript codebase to TypeScript. +ここで紹介するのは、JavaScriptのコードベースからTypeScriptに移植された可能性がある既存のビルドインフラストラクチャを持つプロジェクトでよく見られるパターンです。 -This technique is a hybrid approach, using Babel's [preset-typescript](https://babeljs.io/docs/en/babel-preset-typescript) to generate your JS files, and then using TypeScript to do type checking and `.d.ts` file generation. +このテクニックは、Babelの[preset-typescript](https://babeljs.io/docs/en/babel-preset-typescript)を使ってJSファイルを生成し、次にTypeScriptを用いて型チェックと`.d.ts`ファイルの生成を行うというハイブリッドなアプローチです。 -By using babel's support for TypeScript, you get the ability to work with existing build pipelines and are more likely to have a faster JS emit time because Babel does not type check your code. +BabelのTypeScriptサポートを活用することで、既存のビルドパイプラインとの連携が可能になり、また、Babelはコードの型チェックを行わないため、JS出力にかかる時間が短縮できる可能性が高まります。 -#### Type Checking and d.ts file generation +#### 型チェックとd.tsファイルの生成 -The downside to using babel is that you don't get type checking during the transition from TS to JS. This can mean that type errors which you miss in your editor could sneak through into production code. +Babelを使う際の欠点としては、TSからJSへのトランスパイルを行う際に型チェックを受けられないことがあります。これは、エディタで見逃した型エラーが本番コードに潜り込んでしまうかもしれないことを意味します。 -In addition to that, Babel cannot create `.d.ts` files for your TypeScript which can make it harder to work with your project if it is a library. +加えて、BabelはTypeScript用の`.d.ts`ファイルを生成することができないため、プロジェクトがライブラリである場合、そのライブラリを扱うのが難しくなる可能性があります。 -To fix these issues, you would probably want to set up a command to type check your project using TSC. This likely means duplicating some of your babel config into a corresponding [`tsconfig.json`](/tsconfig) and ensuring these flags are enabled: +こうした問題を解決するには、TSCを使ってプロジェクトの型チェックを行うコマンドを設定する必要があります。これはおそらく、Babelの設定の一部を対応する[`tsconfig.json`](/tsconfig)にコピーし、次のフラグが有効になっていることを確認することになるでしょう: ```json tsconfig "compilerOptions": { - // Ensure that .d.ts files are created by tsc, but not .js files + // tscによって.d.tsファイルを作成させますが、.jsファイルは作成されないようにします "declaration": true, "emitDeclarationOnly": true, - // Ensure that Babel can safely transpile files in the TypeScript project + // BabelがTypeScriptプロジェクト内のファイルを安全にトランスパイルできるようにします "isolatedModules": true } ``` -For more information on these flags: +上記のフラグの詳細についてはこちらをご確認ください: - [`isolatedModules`](/tsconfig#isolatedModules) -- [`declaration`](/tsconfig#declaration), [`emitDeclarationOnly`](/tsconfig#emitDeclarationOnly) +- [`declaration`](/tsconfig#declaration)、[`emitDeclarationOnly`](/tsconfig#emitDeclarationOnly) diff --git a/docs/documentation/ja/tutorials/DOM Manipulation.md b/docs/documentation/ja/tutorials/DOM Manipulation.md index 9344bb0b..6fcc7170 100755 --- a/docs/documentation/ja/tutorials/DOM Manipulation.md +++ b/docs/documentation/ja/tutorials/DOM Manipulation.md @@ -1,26 +1,26 @@ --- -title: DOM Manipulation +title: DOMの操作 layout: docs -permalink: /docs/handbook/dom-manipulation.html -oneline: Using the DOM with TypeScript +permalink: /ja/docs/handbook/dom-manipulation.html +oneline: TypeScriptでDOMを扱う translatable: true --- -## DOM Manipulation +## DOMの操作 -### _An exploration into the `HTMLElement` type_ +### _`HTMLElement`型の探索_ -In the 20+ years since its standardization, JavaScript has come a very long way. While in 2020, JavaScript can be used on servers, in data science, and even on IoT devices, it is important to remember its most popular use case: web browsers. +標準化されてから20年以上の間に、JavaScriptは非常に長い道のりを歩んできました。2020年には、JavaScriptはサーバー上、データサイエンス、さらにはIoTデバイスでさえも使用できるようになりましたが、最も一般的なユースケースであるWebブラウザについて覚えておくことが重要です。 -Websites are made up of HTML and/or XML documents. These documents are static, they do not change. The *Document Object Model (DOM)* is a programming interface implemented by browsers in order to make static websites functional. The DOM API can be used to change the document structure, style, and content. The API is so powerful that countless frontend frameworks (jQuery, React, Angular, etc.) have been developed around it in order to make dynamic websites even easier to develop. +Webサイトは、HTMLおよびXMLドキュメントで構成されています。これらのドキュメントは静的で、変化しません。_Document Object Model (DOM)_ は、静的なWebサイトを機能的にするためにブラウザによって実装されたプログラミングインターフェースです。DOM APIは、ドキュメントの構造、スタイル、そして内容を変更するために使うことができます。このAPIはとても強力なので、動的なWebサイトを簡単に作成するために数え切れないほど多くのフロントエンドフレームワーク(jQuery、React、Angularなど)が開発されてきました。 -TypeScript is a typed superset of JavaScript, and it ships type definitions for the DOM API. These definitions are readily available in any default TypeScript project. Of the 20,000+ lines of definitions in _lib.dom.d.ts_, one stands out among the rest: `HTMLElement` . This type is the backbone for DOM manipulation with TypeScript. +TypeScriptはJavaScriptの型付きスーパーセットであり、DOM APIの型定義を提供しています。こうした定義はあらゆるデフォルトのTypeScriptプロジェクトでもすぐに利用できるようになっています。20,000行を超える _lib.dom.d.ts_ の定義の中で、ひときわ目立つものがあります。それが`HTMLElement`です。この型はTypeScriptでのDOM操作の根幹となるものです。 -> You can explore the source code for the [DOM type definitions](https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts) +> [DOMの型定義](https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts)のソースコードを細かく調べることができます -## Basic Example +## 基本的な例 -Given a simplified _index.html_ file: +次のような単純化された _index.html_ ファイルがあるとします: @@ -32,23 +32,23 @@ Given a simplified _index.html_ file: -Lets explore a TypeScript script that adds a `

Hello, World

` element to the `#app` element. +`#app`要素に`

Hello, World

`要素を追加するTypeScriptのスクリプトを見てみましょう。 ```ts -// 1. Select the div element using the id property +// 1. idプロパティを使ってdiv要素を選択します const app = document.getElementById("app"); -// 2. Create a new

element programmatically +// 2. プログラムによって新しい

要素を作成します const p = document.createElement("p"); -// 3. Add the text content +// 3. テキストの内容を追加します p.textContent = "Hello, World!"; -// 4. Append the p element to the div element +// 4. p要素をdiv要素に追加します app?.appendChild(p); ``` -After compiling and running the _index.html_ page, the resulting HTML will be: +コンパイルして、 _index.html_ ページを開くと、HTMLは結果的に次のようになります: ```html
@@ -56,36 +56,36 @@ After compiling and running the _index.html_ page, the resulting HTML will be:
``` -## The `Document` Interface +## `Document`インターフェース -The first line of the TypeScript code uses a global variable `document`. Inspecting the variable shows it is defined by the `Document` interface from the _lib.dom.d.ts_ file. The code snippet contains calls to two methods, `getElementById` and `createElement`. +TypeScriptの最初の行では、グローバル変数`document`を使用しています。この変数を調べてみると、_lib.dom.d.ts_ ファイルの`Document`インターフェースで定義されていることが分かります。コードスニペットには、`getElementById`と`createElement`の2つのメソッドの呼び出しが含まれています。 ### `Document.getElementById` -The definition for this method is as follows: +このメソッドの定義は次のとおりです: ```ts getElementById(elementId: string): HTMLElement | null; ``` -Pass it an element id string and it will return either `HTMLElement` or `null` . This method introduces one of the most important types, `HTMLElement`. It serves as the base interface for every other element interface. For example, the `p` variable in the code example is of type `HTMLParagraphElement`. Also take note that this method can return `null`. This is because the method can't be certain pre-runtime if it will be able to actually find the specified element or not. In the last line of the code snippet, the new _optional chaining_ operator is used in order to call `appendChild`. +要素のid文字列を渡し、`HTMLElement`あるいは`null`を返します。このメソッドによって、最も重要な型のひとつである`HTMLElement`が導かれます。この型は他のすべての要素のインターフェースのベースとなるインターフェースとして機能します。例えば、前述のコード例の変数`p`は、`HTMLParagraphElement`型です。また、このメソッドは`null`を返す可能性があることにも注意してください。これは、指定された要素を実際に見つけることができるかどうか、このメソッドの実行前には保証できないためです。コードスニペットの最後の行では、`appendChild`を呼び出すために、新機能の _オプショナルチェイニング_ 演算子を用いています。 ### `Document.createElement` -The definition for this method is (I have omitted the _deprecated_ definition): +このメソッドの定義は次のとおりです (_非推奨の_ 定義は省略しています): ```ts createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; ``` -This is an overloaded function definition. The second overload is simplest and works a lot like the `getElementById` method does. Pass it any `string` and it will return a standard HTMLElement. This definition is what enables developers to create unique HTML element tags. +この関数の定義はオーバーロードされています。2番目のオーバーロードは最も単純で、`getElementById`と非常に似た動作を行います。任意の`string`を渡すと、標準のHTMLElementを返します。この定義により、開発者はユニークなHTML要素のタグを作成することができます。 -For example `document.createElement('xyz')` returns a `` element, clearly not an element that is specified by the HTML specification. +例えば、`document.createElement('xyz')`は``要素を返しますが、これは明らかにHTMLの仕様で指定された要素ではありません。 -> For those interested, you can interact with custom tag elements using the `document.getElementsByTagName` +> 興味ある方は、`document.getElementsByTagName`を使用してカスタムタグ要素に触れてみてください -For the first definition of `createElement`, it is using some advanced generic patterns. It is best understood broken down into chunks, starting with the generic expression: ``. This expression defines a generic parameter `K` that is _constrained_ to the keys of the interface `HTMLElementTagNameMap`. The map interface contains every specified HTML tag name and its corresponding type interface. For example here are the first 5 mapped values: +`createElement`の最初の定義では、複数の高度なジェネリクスパターンを使用しています。これはチャンクに分けて理解するのが最良です。まずは、ジェネリクス式``から見ていきます。この式は`HTMLElementTagNameMap`のキーに **制限された** ジェネリクスパラメータ`K`を定義しています。マップインターフェースは、指定されたすべてのHTMLタグ名とそれに対応するすべての型インターフェースを含みます。例えば、マップされた値の最初の5つは次のとおりです: ```ts interface HTMLElementTagNameMap { @@ -98,27 +98,27 @@ interface HTMLElementTagNameMap { } ``` -Some elements do not exhibit unique properties and so they just return `HTMLElement`, but other types do have unique properties and methods so they return their specific interface (which will extend from or implement `HTMLElement`). +固有のプロパティを持たない要素は`HTMLElement`を返すだけですが、そうでない型は、(`HTMLElement`を拡張あるいは実装した)特定のインターフェースを返します。 -Now, for the remainder of the `createElement` definition: `(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]`. The first argument `tagName` is defined as the generic parameter `K` . The TypeScript interpreter is smart enough to _infer_ the generic parameter from this argument. This means that the developer does not actually have to specify the generic parameter when using the method; whatever value is passed to the `tagName` argument will be inferred as `K` and thus can be used throughout the remainder of the definition. Which is exactly what happens; the return value `HTMLElementTagNameMap[K]` takes the `tagName` argument and uses it to return the corresponding type. This definition is how the `p` variable from the code snippet gets a type of `HTMLParagraphElement`. And if the code was `document.createElement('a')`, then it would be an element of type `HTMLAnchorElement`. +さて、`createElement`定義の残りの部分、`(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]`についてですが、第一引数 `tagName`はジェネリクスパラメータ`K`として定義されています。TypeScriptのインタープリタは、十分に精度が高いのでこの引数からジェネリクスパラメータを _推測_ することができます。開発者がこのメソッドを使うときには、実際にはジェネリクスパラメータを指定する必要がない、ということです。`tagName`引数に渡された値がなんであれ、`K`として推測され、定義の残りの部分を通してずっと使用することができます。その結果次のようなことが起こります。戻り値`HTMLElementTagNameMap[K]`は`tagName`引数を取り、それを使って対応する型を返します。この定義によって、前述のコードスニペットの`p`変数は`HTMLParagraphElement`型を取得します。また、もしコードが`document.createElement('a')`であったならば、`HTMLAnchorElement`型の要素となっていました。 -## The `Node` interface +## `Node`インターフェース -The `document.getElementById` function returns an `HTMLElement`. `HTMLElement` interface extends the `Element` interface which extends the `Node` interface. This prototypal extension allows for all `HTMLElements` to utilize a subset of standard methods. In the code snippet, we use a property defined on the `Node` interface to append the new `p` element to the website. +`document.getElementById`関数は`HTMLElement`を返します。`HTMLElement`は、`Node`インターフェースを拡張した`Element`インターフェースを拡張したものです。このプロトタイプの拡張により、すべての`HTMLElements`が標準メソッドのサブセットを活用できます。前述のコードスニペットでは、`Node`インターフェースで定義されたプロパティを使って新しい`p`要素をWebサイトに追加しています。 ### `Node.appendChild` -The last line of the code snippet is `app?.appendChild(p)`. The previous, `document.getElementById` , section detailed that the _optional chaining_ operator is used here because `app` can potentially be null at runtime. The `appendChild` method is defined by: +コードスニペットの最後の行は`app?.appendChild(p)`です。前述の`document.getElementById`のセクションでは、実行時に`app`がnullになる可能性があるため、ここでは _オプショナルチェイニング_ 演算子を用いることを説明しました。`appendChild`は次のように定義されています: ```ts appendChild(newChild: T): T; ``` -This method works similarly to the `createElement` method as the generic parameter `T` is inferred from the `newChild` argument. `T` is _constrained_ to another base interface `Node`. +このメソッドは`createElement`メソッドと同様に動作し、ジェネリクスパラメータ`T`は `newChild`引数から推測されます。`T`は別の基底インターフェースである`Node`に _制限_ されています。 -## Difference between `children` and `childNodes` +## `children`と`childNodes`の違い -Previously, this document details the `HTMLElement` interface extends from `Element` which extends from `Node`. In the DOM API there is a concept of _children_ elements. For example in the following HTML, the `p` tags are children of the `div` element +前のセクションでは、`HTMLElement`インターフェースは、`Node`を拡張した`Element`を拡張したものであることについて説明しました。DOM APIには、_子_ 要素というものがあり、例えば、次のHTMLでは、`p`タグは`div`要素の子です。 ```tsx
@@ -135,9 +135,9 @@ div.childNodes; // NodeList(2) [p, p] ``` -After capturing the `div` element, the `children` prop will return a `HTMLCollection` list containing the `HTMLParagraphElements`. The `childNodes` property will return a similar `NodeList` list of nodes. Each `p` tag will still be of type `HTMLParagraphElements`, but the `NodeList` can contain additional _HTML nodes_ that the `HTMLCollection` list cannot. +`div`要素を取得した後、`children`プロパティは、`HTMLParagraphElements`を含むリストである`HTMLCollection`を返します。`childNodes`プロパティは、同様のノードのリストである`NodeList`を返します。それぞれの`p`タグは`HTMLParagraphElements`型のままですが、`NodeList`は`HTMLCollection`リストにはない _HTMLノード_ を含めることができます。 -Modify the html by removing one of the `p` tags, but keep the text. +テキストは保ったまま、一方の`p`タグを削除してHTMLを変更してみましょう。 ```tsx
@@ -154,31 +154,31 @@ div.childNodes; // NodeList(2) [p, text] ``` -See how both lists change. `children` now only contains the `

Hello, World

` element, and the `childNodes` contains a `text` node rather than two `p` nodes. The `text` part of the `NodeList` is the literal `Node` containing the text `TypeScript!`. The `children` list does not contain this `Node` because it is not considered an `HTMLElement`. +両方のリストがどのように変化するか見てみましょう。`children`には、`

Hello, World

`要素だけが含まれるようになり、`childNodes`には、2つの`p`ノードの代わりに、`text`ノードが含まれるようになりました。`NodeList`の`text`の部分は、テキストである `TypeScript!`を含むリテラル`Node`です。この`Node`は`HTMLElement`とはみなされないため、`children`リストには含まれていません。 -## The `querySelector` and `querySelectorAll` methods +## `querySelector`と`querySelectorAll`メソッド -Both of these methods are great tools for getting lists of dom elements that fit a more unique set of constraints. They are defined in _lib.dom.d.ts_ as: +これらのメソッドは、どちらもよりユニークな制約に適合するDOM要素のリストを取得するための優れたツールです。_lib.dom.d.ts_ において、次のように定義されています: ```ts /** - * Returns the first element that is a descendant of node that matches selectors. + * セレクタにマッチするノードの子孫である最初の要素を返します。 */ querySelector(selectors: K): HTMLElementTagNameMap[K] | null; querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; /** - * Returns all element descendants of node that match selectors. + * セレクタにマッチするノードの子孫であるすべての要素を返します。 */ querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; ``` -The `querySelectorAll` definition is similar to `getElementsByTagName`, except it returns a new type: `NodeListOf`. This return type is essentially a custom implementation of the standard JavaScript list element. Arguably, replacing `NodeListOf` with `E[]` would result in a very similar user experience. `NodeListOf` only implements the following properties and methods: `length` , `item(index)`, `forEach((value, key, parent) => void)` , and numeric indexing. Additionally, this method returns a list of _elements_, not _nodes_, which is what `NodeList` was returning from the `.childNodes` method. While this may appear as a discrepancy, take note that interface `Element` extends from `Node`. +`querySelectorAll`の定義は、新しい型`NodeListOf`を返すという点以外は `getElementsByTagName`と似ています。この戻り値の型は、基本的には標準的なJavaScriptのリスト要素のカスタム実装です。まず間違いなく、`NodeListOf`を`E[]`と置き換えても、非常によく似たユーザー体験が得られるでしょう。`NodeListOf`は、`length` 、`item(index)`、`forEach((value, key, parent) => void)`、数値インデックスといったプロパティとメソッドのみを実装しています。加えて、このメソッドは`NodeList`が`.childNodes`メソッドから返していた _ノード_ ではなく、_要素_ のリストを返します。これは矛盾しているようにみえるかもしれませんが、`Element`インターフェースが`Node`を拡張したものであることを思い出してください。 -To see these methods in action modify the existing code to: +上記のメソッドの実際の動作を確認するために、既存のコードを次のように変更しましょう: ```tsx
    @@ -187,15 +187,15 @@ To see these methods in action modify the existing code to:
  • Third times a charm.
; -const first = document.querySelector("li"); // returns the first li element -const all = document.querySelectorAll("li"); // returns the list of all li elements +const first = document.querySelector("li"); // 最初のli要素を返す +const all = document.querySelectorAll("li"); // すべてのli要素のリストを返す ``` -## Interested in learning more? +## もっと知りたいですか? -The best part about the _lib.dom.d.ts_ type definitions is that they are reflective of the types annotated in the Mozilla Developer Network (MDN) documentation site. For example, the `HTMLElement` interface is documented by this [HTMLElement page](https://developer.mozilla.org/docs/Web/API/HTMLElement) on MDN. These pages list all available properties, methods, and sometimes even examples. Another great aspect of the pages is that they provide links to the corresponding standard documents. Here is the link to the [W3C Recommendation for HTMLElement](https://www.w3.org/TR/html52/dom.html#htmlelement). +_lib.dom.d.ts_ の型定義の最も良いところは、Mozilla Developer Network (MDN)のドキュメントサイトで注釈されている型を反映しているところです。例えば、`HTMLElement`は[HTMLElementページ](https://developer.mozilla.org/docs/Web/API/HTMLElement)に記載されています。こうしたページには、利用可能なすべてのプロパティ、メソッド、時には例さえもリストしています。こうしたページの、もう1つ素晴らしいところは、対応する標準ドキュメントのリンクを掲載している点です。上記のページには[HTMLElementのW3C勧告](https://www.w3.org/TR/html52/dom.html#htmlelement)のリンクがあります。 -Sources: +資料: - [ECMA-262 Standard](http://www.ecma-international.org/ecma-262/10.0/index.html) -- [Introduction to the DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) +- [DOMの紹介](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) diff --git a/docs/documentation/ja/tutorials/Migrating from JavaScript.md b/docs/documentation/ja/tutorials/Migrating from JavaScript.md index be31153a..d8bdafe9 100644 --- a/docs/documentation/ja/tutorials/Migrating from JavaScript.md +++ b/docs/documentation/ja/tutorials/Migrating from JavaScript.md @@ -1,31 +1,31 @@ --- -title: Migrating from JavaScript +title: JavaScriptからの移行 layout: docs -permalink: /docs/handbook/migrating-from-javascript.html -oneline: How to migrate from JavaScript to TypeScript +permalink: /ja/docs/handbook/migrating-from-javascript.html +oneline: JavaScriptからTypeScriptに移行する方法 --- -TypeScript doesn't exist in a vacuum. -It was built with the JavaScript ecosystem in mind, and a lot of JavaScript exists today. -Converting a JavaScript codebase over to TypeScript is, while somewhat tedious, usually not challenging. -In this tutorial, we're going to look at how you might start out. -We assume you've read enough of the handbook to write new TypeScript code. +TypeScriptはそれ単独で存在しているわけではありません。 +JavaScriptのエコシステムを念頭において構築されたものであり、今日ではたくさんのJavaScriptが存在しています。 +JavaScriptのコードベースをTypeScriptに移行することは、多少面倒ですが、通常は難しくはありません。 +本チュートリアルでは、どのようにして移行を開始するのが良いのかについて見ていきましょう。 +新しいTypeScriptコードを記述するためのハンドブックを十分読み込んだことを前提としています。 -If you're looking to convert a React project, we recommend looking at the [React Conversion Guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide) first. +Reactプロジェクトでの移行を考えているのであれば、まずは[React Conversion Guide](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide)を読むことをおすすめします。 -## Setting up your Directories +## ディレクトリの設定 -If you're writing in plain JavaScript, it's likely that you're running your JavaScript directly, -where your `.js` files are in a `src`, `lib`, or `dist` directory, and then ran as desired. +素のJavaScriptを書いているならば、JavaScriptを直接実行している可能性が高いです。 +この場合、`.js`ファイルは`src`、`lib`、あるいは`dist`ディレクトリに置かれ、必要に応じて実行されていることでしょう。 -If that's the case, the files that you've written are going to be used as inputs to TypeScript, and you'll run the outputs it produces. -During our JS to TS migration, we'll need to separate our input files to prevent TypeScript from overwriting them. -If your output files need to reside in a specific directory, then that will be your output directory. +こうしたケースでは、記述したファイルはTypeScriptの入力として使用され、TypeScriptが生成する出力を実行することになります。 +JSからTSへの移行中、TypeScriptが入力ファイルを上書きしないように入力ファイルを分離する必要があります。 +出力ファイルを特定のディレクトリに置く必要がある場合、そのディレクトリが出力ディレクトリとなります。 -You might also be running some intermediate steps on your JavaScript, such as bundling or using another transpiler like Babel. -In this case, you might already have a folder structure like this set up. +バンドルしたり、Babelのような別のトランスパイラを使ったり、JavaScriptに対して中間ステップを実行していることがあるかもしれません。 +この場合は、すでに上述したようなフォルダ構成が設定されている可能性があります。 -From this point on, we're going to assume that your directory is set up something like this: +ここからは、ディレクトリが次のように設定されていると仮定します: ``` projectRoot @@ -36,12 +36,12 @@ projectRoot └── tsconfig.json ``` -If you have a `tests` folder outside of your `src` directory, you might have one `tsconfig.json` in `src`, and one in `tests` as well. +`src`ディレクトリの外に`tests`フォルダがある場合、`src`の中に`tsconfig.json`をひとつ置き、`tests`の中にもひとつ置くことができます。 -## Writing a Configuration File +## 設定ファイルの記述 -TypeScript uses a file called `tsconfig.json` for managing your project's options, such as which files you want to include, and what sorts of checking you want to perform. -Let's create a bare-bones one for our project: +TypeScriptは、どのファイルを含めたいのか、どの種類のチェックを実行したいのかといったプロジェクトの設定を管理する`tsconfig.json`と呼ばれるファイルを使用します。 +プロジェクトにとって必要最低限の設定ファイルを作成してみましょう: ```json { @@ -54,50 +54,50 @@ Let's create a bare-bones one for our project: } ``` -Here we're specifying a few things to TypeScript: +上記では、TypeScriptに対して数点指定しています: -1. Read in any files it understands in the `src` directory (with `include`). -2. Accept JavaScript files as inputs (with `allowJs`). -3. Emit all of the output files in `built` (with `outDir`). -4. Translate newer JavaScript constructs down to an older version like ECMAScript 5 (using `target`). +1. `src`ディレクトリにある解釈可能なファイルを読み込む(`include`にて) +2. JavaScriptファイルを入力ファイルとして許可する(`allowJs`にて) +3. `built`ディレクトリにすべての出力ファイルを出力する(`outDir`にて) +4. 新しいJavaScriptの構造をECMAScript5のようなより古いバージョンに変換する(`target`にて) -At this point, if you try running `tsc` at the root of your project, you should see output files in the `built` directory. -The layout of files in `built` should look identical to the layout of `src`. -You should now have TypeScript working with your project. +この時点でプロジェクトのルートで`tsc`を実行してみると、`built`ディレクトリに出力ファイルが確認できるはずです。 +`built`にあるファイルのレイアウトは`src`のものと同じように見えるでしょう。 +これで、あなたのプロジェクトにおいて、TypeScriptが動作するようになりました。 -## Early Benefits +## 初期に導入することによるメリット -Even at this point you can get some great benefits from TypeScript understanding your project. -If you open up an editor like [VS Code](https://code.visualstudio.com) or [Visual Studio](https://visualstudio.com), you'll see that you can often get some tooling support like completion. -You can also catch certain bugs with options like: +この段階でも、TypeScriptがあなたのプロジェクトを理解することで受けられるメリットがいくつかあります。 +[VS Code](https://code.visualstudio.com)や[Visual Studio](https://visualstudio.com)のようなエディタを開くと、補完などのツールによるサポートをたびたび受けられることが確認できるでしょう。 +また、以下のようなオプションを設定することで、特定のバグを発見することもできます: -- `noImplicitReturns` which prevents you from forgetting to return at the end of a function. -- `noFallthroughCasesInSwitch` which is helpful if you never want to forget a `break` statement between `case`s in a `switch` block. +- `noImplicitReturns`は、関数の最後の戻り値の設定忘れを防止します。 +- `noFallthroughCasesInSwitch`は、`switch`ブロックの`case`間で`break`文を忘れたくない時に便利です。 -TypeScript will also warn about unreachable code and labels, which you can disable with `allowUnreachableCode` and `allowUnusedLabels` respectively. +TypeScriptは、到達不可能なコードやラベルについても警告します。この警告は、それぞれ`allowUnreachableCode`と`allowUnusedLabels`でオフにできます。 -## Integrating with Build Tools +## ビルドツールとの統合 -You might have some more build steps in your pipeline. -Perhaps you concatenate something to each of your files. -Each build tool is different, but we'll do our best to cover the gist of things. +パイプラインにもっと多くのビルドステップが存在しているかもしれません。 +もしかしたらそれぞれのファイルに何か他のファイルを連結していることもあるでしょう。 +それぞれビルドツールは異なりますが、ここではその要点をできる限りカバーします。 ## Gulp -If you're using Gulp in some fashion, we have a tutorial on [using Gulp](/docs/handbook/gulp.html) with TypeScript, and integrating with common build tools like Browserify, Babelify, and Uglify. -You can read more there. +Gulpを何らかの方法で使用してる場合は、TypeScriptと[Gulpの使用](/docs/handbook/gulp.html)について、およびBrowserify、Babelify、Uglifyといった一般的なビルドツールとの統合についてのチュートリアルがあります。 +詳しくはそちらをご確認ください。 ## Webpack -Webpack integration is pretty simple. -You can use `ts-loader`, a TypeScript loader, combined with `source-map-loader` for easier debugging. -Simply run +Webpackとの統合はとても簡単です。 +TypeScriptローダーである`ts-loader`と、デバッグを簡単にするための`source-map-loader`を組み合わせることができます。 +次のコマンドを実行します ```shell npm install ts-loader source-map-loader ``` -and merge in options from the following into your `webpack.config.js` file: +そして、以下のオプションを`webpack.config.js`ファイルにマージします: ```js module.exports = { @@ -106,88 +106,88 @@ module.exports = { filename: "./dist/bundle.js", }, - // Enable sourcemaps for debugging webpack's output. + // webpack の出力をデバッグするためのソースマップを有効にします。 devtool: "source-map", resolve: { - // Add '.ts' and '.tsx' as resolvable extensions. + // 解決可能な拡張子として'.ts'と'.tsx'を追加します。 extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"], }, module: { rules: [ - // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. + // '.ts'または'.tsx'拡張子を持つすべてのファイルは'ts-loader'によって処理されます。 { test: /\.tsx?$/, loader: "ts-loader" }, - // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. + // 出力されるすべての'.js'ファイルは'source-map-loader'によって再処理されたソースマップを持ちます。 { test: /\.js$/, loader: "source-map-loader" }, ], }, - // Other options... + // その他のオプション... }; ``` -It's important to note that ts-loader will need to run before any other loader that deals with `.js` files. +重要なのは、`.js`ファイルを扱う他のどのローダーよりも先に、ts-loaderを実行する必要があるという点です。 -The same goes for [awesome-typescript-loader](https://github.com/TypeStrong/ts-loader), another TypeScript loader for Webpack. -You can read more about the differences between the two [here](https://github.com/s-panferov/awesome-typescript-loader#differences-between-ts-loader). +WebpackのもうひとつのTypeScriptローダーである[awesome-typescript-loader](https://github.com/TypeStrong/ts-loader)でも同様です。 +この2つの違いについては、[こちら](https://github.com/s-panferov/awesome-typescript-loader#differences-between-ts-loader)を参照してください。 -You can see an example of using Webpack in our [tutorial on React and Webpack](/docs/handbook/react-&-webpack.html). +Webpackを使用している例は、[ReactとWebpackのチュートリアル](/docs/handbook/react-&-webpack.html)で確認することができます。 -## Moving to TypeScript Files +## TypeScriptファイルに移行する -At this point, you're probably ready to start using TypeScript files. -The first step is to rename one of your `.js` files to `.ts`. -If your file uses JSX, you'll need to rename it to `.tsx`. +ここまでで、TypeScriptファイルを使い始める準備ができたことでしょう。 +移行の最初のステップとして、`.js`ファイルを`.ts`にリネームします。 +もしファイルがJSXを使用している場合は、`.tsx`にリネームする必要があります。 -Finished with that step? -Great! -You've successfully migrated a file from JavaScript to TypeScript! +このステップを終えましたか? +いいですね! +これでJavaScriptからTypeScriptへのファイルの移行に成功しました! -Of course, that might not feel right. -If you open that file in an editor with TypeScript support (or if you run `tsc --pretty`), you might see red squiggles on certain lines. -You should think of these the same way you'd think of red squiggles in an editor like Microsoft Word. -TypeScript will still translate your code, just like Word will still let you print your documents. +もちろん、このステップが正しくないと思うかもしれません。 +TypeScriptサポートがあるエディタでファイルを開く(あるいは `tsc --pretty` を実行する)と、特定の行に赤い波線が表示されている可能性があります。 +これは、Microsoft Wordようなエディタの赤い波線と同じように考えてください。 +赤い波線があってもWordで文書を印刷することができるのと同じように、赤い波線があってもTypeScriptはコードを変換します。 -If that sounds too lax for you, you can tighten that behavior up. -If, for instance, you _don't_ want TypeScript to compile to JavaScript in the face of errors, you can use the `noEmitOnError` option. -In that sense, TypeScript has a dial on its strictness, and you can turn that knob up as high as you want. +これが手抜きだと思うならば、このふるまいを厳しくすることができます。 +例えば、エラーがあるときはTypeScriptにJavaScriptへのコンパイルを _させたくない_ 場合、`noEmitOnError`オプションを使うことができます。 +そうした意味では、TypeScriptには厳しさの調整つまみがあり、そのつまみを好きなだけ強くすることができると言えます。 -If you plan on using the stricter settings that are available, it's best to turn them on now (see [Getting Stricter Checks](#getting-stricter-checks) below). -For instance, if you never want TypeScript to silently infer `any` for a type without you explicitly saying so, you can use `noImplicitAny` before you start modifying your files. -While it might feel somewhat overwhelming, the long-term gains become apparent much more quickly. +もし利用可能なより厳しい設定を使用するつもりならば、今のうちに設定を有効化しておくのがベストです(後述の[より厳密なチェック](#getting-stricter-checks)を確認してください)。 +例えば、明示的に指定していない型をTypeScriptが`any`と暗黙的に推測することを望まない場合、ファイルの修正を始める前に`noImplicitAny`を使いましょう。 +修正すべきコードが多くて多少困惑するかもしれませんが、長期的な利益をかなり早い時点で受けることができます。 -## Weeding out Errors +## エラーの除去 -Like we mentioned, it's not unexpected to get error messages after conversion. -The important thing is to actually go one by one through these and decide how to deal with the errors. -Often these will be legitimate bugs, but sometimes you'll have to explain what you're trying to do a little better to TypeScript. +前述したように、変換後にエラーメッセージが出ることは予測できないことではありません。 +重要なことは、実際にエラーをひとつひとつ確認して、そのエラーにどう対処するかを決めることです。 +多くの場合、これらは妥当なバグなのですが、時には何をしようとしているのかをTypeScriptにもう少し上手に説明しなければならないこともあるでしょう。 -### Importing from Modules +### Modulesからのインポート -You might start out getting a bunch of errors like `Cannot find name 'require'.`, and `Cannot find name 'define'.`. -In these cases, it's likely that you're using modules. -While you can just convince TypeScript that these exist by writing out +最初は、`Cannot find name 'require'.`や`Cannot find name 'define'.`といったエラーがたくさん表示されるかもしれません。 +このようなケースでは、おそらくモジュールを使用していることでしょう。 +これらの呼び出しが存在していることをTypeScriptに確信させるには、次のようなコードや ```ts -// For Node/CommonJS +// Node/CommonJS用 declare function require(path: string): any; ``` -or +あるいは次のようなコード ```ts -// For RequireJS/AMD +// RequireJS/AMD用 declare function define(...args: any[]): any; ``` -it's better to get rid of those calls and use TypeScript syntax for imports. +を記述することもできますが、これらの呼び出しを削除し、インポートにはTypeScriptの構文を使った方が良いでしょう。 -First, you'll need to enable some module system by setting TypeScript's `module` flag. -Valid options are `commonjs`, `amd`, `system`, and `umd`. +まず、TypeScriptの`module`フラグを設定してモジュールシステムを有効化する必要があります。 +有効なオプションは、`commonjs`、`amd`、`system`そして`umd`です。 -If you had the following Node/CommonJS code: +以下のようなNode/CommonJSコード: ```js var foo = require("foo"); @@ -195,7 +195,7 @@ var foo = require("foo"); foo.doStuff(); ``` -or the following RequireJS/AMD code: +あるいは次のような RequireJS/AMDコードがあったとします: ```js define(["foo"], function (foo) { @@ -203,7 +203,7 @@ define(["foo"], function (foo) { }); ``` -then you would write the following TypeScript code: +その場合、次のようなTypeScriptコードを記述することになります: ```ts import foo = require("foo"); @@ -211,26 +211,26 @@ import foo = require("foo"); foo.doStuff(); ``` -### Getting Declaration Files +### 宣言ファイルの取得 -If you started converting over to TypeScript imports, you'll probably run into errors like `Cannot find module 'foo'.`. -The issue here is that you likely don't have _declaration files_ to describe your library. -Luckily this is pretty easy. -If TypeScript complains about a package like `lodash`, you can just write +TypeScriptのインポートに変換し始めた場合、おそらく`Cannot find module 'foo'.`といったエラーに遭遇するでしょう。 +ここでの問題は、ライブラリを記述するための _宣言ファイル_ を持っていないことです。 +幸運なことに、これはとても簡単に解決できます。 +TypeScriptが`lodash`のようなパッケージについて文句を言ってきたら、ただ次のように記述すればよいのです ```shell npm install -S @types/lodash ``` -If you're using a module option other than `commonjs`, you'll need to set your `moduleResolution` option to `node`. +もし、`commonjs`以外のモジュールオプションを使用しているならば、`moduleResolution`オプションに`node`を設定する必要があるでしょう。 -After that, you'll be able to import lodash with no issues, and get accurate completions. +これで、問題なくlodashをインポートして、正確な補完を得ることができます。 -### Exporting from Modules +### モジュールからのエクスポート -Typically, exporting from a module involves adding properties to a value like `exports` or `module.exports`. -TypeScript allows you to use top-level export statements. -For instance, if you exported a function like so: +通常、モジュールからのエクスポートは、`exports`や`module.exports`のような値にプロパティを追加することを必要とします。 +TypeScriptでは、トップレベルのエクスポート宣言を使うことができます。 +例えば、次のような関数をエクスポートしたとします: ```js module.exports.feedPets = function (pets) { @@ -238,7 +238,7 @@ module.exports.feedPets = function (pets) { }; ``` -you could write that out as the following: +これは、次のように記述することもできます: ```ts export function feedPets(pets) { @@ -246,15 +246,15 @@ export function feedPets(pets) { } ``` -Sometimes you'll entirely overwrite the exports object. -This is a common pattern people use to make their modules immediately callable like in this snippet: +時々、exportsオブジェクトを完全に上書きすることがあります。 +これは、以下のスニペットのように、すぐに呼び出すことのできるモジュールを作成するために、よく使われるパターンです: ```js var express = require("express"); var app = express(); ``` -You might have previously written that like so: +以前は次のように記述していたかもしれません: ```js function foo() { @@ -263,7 +263,7 @@ function foo() { module.exports = foo; ``` -In TypeScript, you can model this with the `export =` construct. +TypeScriptでは、`export =`構造体でモデル化することができます。 ```ts function foo() { @@ -272,10 +272,10 @@ function foo() { export = foo; ``` -### Too many/too few arguments +### 多すぎる/少なすぎる引数 -You'll sometimes find yourself calling a function with too many/few arguments. -Typically, this is a bug, but in some cases, you might have declared a function that uses the `arguments` object instead of writing out any parameters: +多すぎる/少なすぎる引数で関数を呼び出していることに気づくことが時々あります。 +通常、これはバグですが、場合によってはパラメータを記述する代わりに`arguments`オブジェクトを使用する関数を宣言しているかもしれません。 ```js function myCoolFunction() { @@ -304,7 +304,7 @@ myCoolFunction( ); ``` -In this case, we need to use TypeScript to tell any of our callers about the ways `myCoolFunction` can be called using function overloads. +この場合、関数のオーバーロードを使って`myCoolFunction`を呼び出すことのできる方法を、呼び出し元に伝えるためにTypeScriptを使用する必要があります。 ```ts function myCoolFunction(f: (x: number) => void, nums: number[]): void; @@ -319,13 +319,13 @@ function myCoolFunction() { } ``` -We added two overload signatures to `myCoolFunction`. -The first checks states that `myCoolFunction` takes a function (which takes a `number`), and then a list of `number`s. -The second one says that it will take a function as well, and then uses a rest parameter (`...nums`) to state that any number of arguments after that need to be `number`s. +2つのオーバーロードシグネチャを`myCoolFunction`に追加しました。 +最初の関数シグネチャは、`myCoolFunction`が(`number`を受け取る)関数を受け取り、次に`number`のリストを受け取ることを示しています。 +二番目は、同様に関数を受け取り、レストパラメータ(`...nums`)を使ってそれ以降の引数は任意の数の`number`である必要があることを示しています。 -### Sequentially Added Properties +### 順次追加されるプロパティ -Some people find it more aesthetically pleasing to create an object and add properties immediately after like so: +次のように、オブジェクトを作成してその後すぐにプロパティを追加するほうが、審美性が高いと思う人もいます: ```js var options = {}; @@ -333,8 +333,8 @@ options.color = "red"; options.volume = 11; ``` -TypeScript will say that you can't assign to `color` and `volume` because it first figured out the type of `options` as `{}` which doesn't have any properties. -If you instead moved the declarations into the object literal themselves, you'd get no errors: +TypeScriptは、`options`型をプロパティを持たない`{}`として最初に理解したので、`color`と`volume`を代入できないと言うでしょう。 +プロパティの宣言をオブジェクトリテラルの中に移動させれば、エラーが発生しません: ```ts let options = { @@ -343,7 +343,7 @@ let options = { }; ``` -You could also define the type of `options` and add a type assertion on the object literal. +また、`options`型を定義して、オブジェクトリテラルに型アサーションを追加することができます。 ```ts interface Options { @@ -356,59 +356,59 @@ options.color = "red"; options.volume = 11; ``` -Alternatively, you can just say `options` has the type `any` which is the easiest thing to do, but which will benefit you the least. +あるいは、`options`は、`any`型であると指定することもできます。これが最も簡単な方法ですが、メリットは最も少ないです。 -### `any`, `Object`, and `{}` +### `any`、`Object`、そして`{}` -You might be tempted to use `Object` or `{}` to say that a value can have any property on it because `Object` is, for most purposes, the most general type. -However **`any` is actually the type you want to use** in those situations, since it's the most _flexible_ type. +`Object`は、ほとんどの場合最も一般的な型なので、値に任意の型を持たせるために、`Object`や`{}`を使いたくなるかもしれません。 +しかし、このような場合では **`any`こそ実際に使用したい型**です。というのも、これこそが最も _柔軟な_ 型だからです。 -For instance, if you have something that's typed as `Object` you won't be able to call methods like `toLowerCase()` on it. -Being more general usually means you can do less with a type, but `any` is special in that it is the most general type while still allowing you to do anything with it. -That means you can call it, construct it, access properties on it, etc. -Keep in mind though, whenever you use `any`, you lose out on most of the error checking and editor support that TypeScript gives you. +例えば、`Object`と型が付けられているものでは、`toLowerCase()`のようなメソッドを呼び出すことはできません。 +より一般的な型であるということは、通常、型でできることは少なくなるということを意味しますが、`any`は最も一般的な型でありながら何でもできるという点で特別です。 +つまり、呼び出したり、コンストラクタとして使えたり、プロパティにアクセスしたりなどができるということです。 +しかし、`any`を使うと常に、TypeScriptが提供するエラーチェックやエディタサポートが失われるということは覚えておいてください。 -If a decision ever comes down to `Object` and `{}`, you should prefer `{}`. -While they are mostly the same, technically `{}` is a more general type than `Object` in certain esoteric cases. +もし、`Object`か`{}`を選ぶことになったら、`{}`を選ぶべきです。 +2つはほとんど同じですが、特定の難解なケースでは`{}`のほうが`Object`より技術的に一般的な型です。 -## Getting Stricter Checks +## より厳密なチェック -TypeScript comes with certain checks to give you more safety and analysis of your program. -Once you've converted your codebase to TypeScript, you can start enabling these checks for greater safety. +TypeScriptには、安全性を高めプログラムの解析を向上させるための、あるチェック機能が備わっています。 +ひとたびコードベースをTypeScriptに変換したら、安全性を高めるために、これらのチェックを有効化することができます。 -### No Implicit `any` +### 暗黙的な`any`の禁止 -There are certain cases where TypeScript can't figure out what certain types should be. -To be as lenient as possible, it will decide to use the type `any` in its place. -While this is great for migration, using `any` means that you're not getting any type safety, and you won't get the same tooling support you'd get elsewhere. -You can tell TypeScript to flag these locations down and give an error with the `noImplicitAny` option. +TypeScriptがある種の型が何であるかを理解できない場合があります。 +できる限り型の選択肢を緩くするために、TypeScriptは代わりに`any`を使うことになるでしょう。 +この決定はTypeScriptへの移行という点では最適ですが、`any`を使うことは型の安全性が得られないということを意味し、他のところで得られていたツールサポートも得られません。 +`noImplicitAny`を使えば、TypeScriptに対してこうした箇所に印をつけてエラーを出すように指示することができます。 -### Strict `null` & `undefined` Checks +### 厳密な`null`と`undefined`チェック -By default, TypeScript assumes that `null` and `undefined` are in the domain of every type. -That means anything declared with the type `number` could be `null` or `undefined`. -Since `null` and `undefined` are such a frequent source of bugs in JavaScript and TypeScript, TypeScript has the `strictNullChecks` option to spare you the stress of worrying about these issues. +デフォルトでは、TypeScriptは`null`と`undefined`があらゆるの型の領域にあると仮定しています。 +つまり、`number`型で宣言されたものはすべて`null`や`undefined`になる可能性があるということです。 +`null`や`undefined`はJavaScriptやTypeScriptで頻繁にバグの原因となるため、TypeScriptには`strictNullChecks`オプションがあり、こういった問題を心配するストレスを軽減してくれます。 -When `strictNullChecks` is enabled, `null` and `undefined` get their own types called `null` and `undefined` respectively. -Whenever anything is _possibly_ `null`, you can use a union type with the original type. -So for instance, if something could be a `number` or `null`, you'd write the type out as `number | null`. +`strictNullChecks`を有効にすると、`null`と`undefined`はそれぞれ`null`と`undefined`という独自の型を取得します。 +何らかの値が`null`である _可能性がある_ 場合は常に元の型とのUnion型を使うことができます。 +例えば、ある値が`number`や`null`になる可能性がある場合、その型を`number | null`と記述します。 -If you ever have a value that TypeScript thinks is possibly `null`/`undefined`, but you know better, you can use the postfix `!` operator to tell it otherwise. +もし、TypeScriptが`null`/`undefined`の可能性があると考えている値があったとしても、あなたがその可能性がないことを知っている場合は、接尾辞`!`演算子を使って、そう伝えることができます。 ```ts declare var foo: string[] | null; -foo.length; // error - 'foo' is possibly 'null' +foo.length; // エラー - 'foo'は'null'の可能性があります -foo!.length; // okay - 'foo!' just has type 'string[]' +foo!.length; // OK - 'foo!'は'string[]'型だけです ``` -As a heads up, when using `strictNullChecks`, your dependencies may need to be updated to use `strictNullChecks` as well. +注意点として、`strictNullChecks`を使う場合は、同様に`strictNullChecks`を使うように依存関係を更新する必要があるかもしれません。 -### No Implicit `any` for `this` +### `this`に対する暗黙的な`any`の禁止 -When you use the `this` keyword outside of classes, it has the type `any` by default. -For instance, imagine a `Point` class, and imagine a function that we wish to add as a method: +クラスの外側で`this`キーワードを使用する場合、デフォルトでは`any`型となります。 +例えば、`Point`クラスがあり、メソッドとして追加したい関数があるとしましょう: ```ts class Point { @@ -421,7 +421,7 @@ class Point { } // ... -// Reopen the interface. +// インターフェースを再定義する interface Point { distanceFromOrigin(): number; } @@ -430,10 +430,10 @@ Point.prototype.distanceFromOrigin = function () { }; ``` -This has the same problems we mentioned above - we could easily have misspelled `getDistance` and not gotten an error. -For this reason, TypeScript has the `noImplicitThis` option. -When that option is set, TypeScript will issue an error when `this` is used without an explicit (or inferred) type. -The fix is to use a `this`-parameter to give an explicit type in the interface or in the function itself: +これは、前述したものと同じ問題があります - `getDistance`のスペルを間違えてしまうかもしれませんし、その場合エラーも出ません。 +このため、TypeScriptには、`noImplicitThis`オプションがあります。 +このオプションが設定されていれば、TypeScriptは、`this`が明示的な(あるいは推測された)型を持たないで使用された場合、エラーを出します。 +修正するには、`this`パラメータを使ってインターフェースや関数自体の中で明示的な型を与えます。 ```ts Point.prototype.distanceFromOrigin = function (this: Point) { diff --git a/docs/documentation/ja/tutorials/React.md b/docs/documentation/ja/tutorials/React.md index 773ea021..0f437908 100644 --- a/docs/documentation/ja/tutorials/React.md +++ b/docs/documentation/ja/tutorials/React.md @@ -1,26 +1,26 @@ --- title: React layout: docs -permalink: /docs/handbook/react.html -oneline: Links to learn about TypeScript and React +permalink: /ja/docs/handbook/react.html +oneline: TypeScriptとReactについて学ぶためのリンク集 translatable: true --- -TypeScript supports [JSX](/docs/handbook/jsx.html) and can correctly model the patterns used in React codebases like `useState`. +TypeScriptは[JSX](/docs/handbook/jsx.html)をサポートしており、`useState`のようなReactコードベースで使用されるパターンを正しくモデル化することができます。 -### Getting Set Up With a React Project +### Reactプロジェクトのセットアップ -Today there are many frameworks which support TypeScript out of the box: +今日では、TypeScriptを標準でサポートしているフレームワークがたくさんあります: - [Create React App](https://create-react-app.dev) - [TS docs](https://create-react-app.dev/docs/adding-typescript/) - [Next.js](https://nextjs.org) - [TS docs](https://nextjs.org/learn/excel/typescript) - [Gatsby](https://www.gatsbyjs.org) - [TS Docs](https://www.gatsbyjs.org/docs/typescript/) -All of these are great starting points. We [use Gatsby](https://www.gatsbyjs.org/blog/2020-01-23-why-typescript-chose-gatsby/#reach-skip-nav) with TypeScript for [this website](https://github.com/microsoft/TypeScript-Website/), so that can also be a useful reference implementation. +これらはすべて、プロジェクトの第一歩としてはとても素晴らしいフレームワークです。[このWebサイト](https://github.com/microsoft/TypeScript-Website/)は、TypeScriptと[Gatsby](https://www.gatsbyjs.org/blog/2020-01-23-why-typescript-chose-gatsby/#reach-skip-nav)を使用しており、これも有用な実装の参考となるでしょう。 -### Documentation +### ドキュメント -Here are some of the best places to find up-to-date information on React and TypeScript: +ReactとTypeScriptの最新情報を見つけるのに最適な情報源をここでいくつか紹介します: - [React TypeScript Cheatsheets](https://react-typescript-cheatsheet.netlify.app) - [React & Redux in TypeScript](https://github.com/piotrwitek/react-redux-typescript-guide#react--redux-in-typescript---complete-guide) diff --git a/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md b/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md index b056c7f3..73b88afd 100644 --- a/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md +++ b/docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md @@ -1,32 +1,32 @@ --- -title: TypeScript Tooling in 5 minutes +title: 5分でわかるTypeScriptツール layout: docs -permalink: /docs/handbook/typescript-tooling-in-5-minutes.html -oneline: A tutorial to understand how to create a small website with TypeScript +permalink: /ja/docs/handbook/typescript-tooling-in-5-minutes.html +oneline: TypeScriptで小さなウェブサイトを作る方法を理解するためのチュートリアル translatable: true --- -Let's get started by building a simple web application with TypeScript. +TypeScriptを使って簡単なWebアプリケーションを作ることからはじめてみましょう。 -## Installing TypeScript +## TypeScriptのインストール -There are two main ways to get the TypeScript available for your project: +プロジェクトでTypeScriptを利用できるようにするには、主に2つの方法があります: -- Via npm (the Node.js package manager) -- By installing TypeScript's Visual Studio plugins +- npm(Node.jsのパッケージマネージャー)を使う +- TypeScriptのVisual Studioプラグインをインストールする -Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. -If you didn't install TypeScript with Visual Studio, you can still [download it](/download). +Visual Studio 2017とVisual Studio 2015 Update 3にはTypeScriptがデフォルトで含まれています。 +Visual StudioにTypeScriptをインストールしなかった場合でも、[ダウンロード](/download)は可能です。 -For npm users: +npmを使う場合はこちら: ```shell > npm install -g typescript ``` -## Building your first TypeScript file +## 初めてのTypeScriptファイルの作成 -In your editor, type the following JavaScript code in `greeter.ts`: +エディタで`greeter.ts`ファイルに次のJavaScriptコードを入力してください: ```ts twoslash // @noImplicitAny: false @@ -39,22 +39,22 @@ let user = "Jane User"; document.body.textContent = greeter(user); ``` -## Compiling your code +## コードのコンパイル -We used a `.ts` extension, but this code is just JavaScript. -You could have copy/pasted this straight out of an existing JavaScript app. +上記で`.ts`拡張子を使いましたが、コードはただのJavaScriptです。 +既存のJavaScriptアプリからそのままコピー/ペーストすることもできます。 -At the command line, run the TypeScript compiler: +コマンドラインで、TypeScriptコンパイラを実行します: ```shell tsc greeter.ts ``` -The result will be a file `greeter.js` which contains the same JavaScript that you fed in. -We're up and running using TypeScript in our JavaScript app! +結果は、先ほど入力したJavaScriptと同じものが含まれた`greeter.js`というファイルになります。 +つまり、JavaScriptアプリ上でTypeScriptを実行しているのです! -Now we can start taking advantage of some of the new tools TypeScript offers. -Add a `: string` type annotation to the 'person' function argument as shown here: +これで、TypeScriptが提供する新しいツールを活用できるようになりました。 +次に示すように、関数の引数'person'に対して`: string`という型注釈を付けてみましょう: ```ts twoslash function greeter(person: string) { @@ -66,11 +66,11 @@ let user = "Jane User"; document.body.textContent = greeter(user); ``` -## Type annotations +## 型注釈 -Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. -In this case, we intend the greeter function to be called with a single string parameter. -We can try changing the call greeter to pass an array instead: +TypeScriptの型注釈は、関数や変数に対する意図的な制約を記録するための軽量な方法です。 +この例では、greeter関数を単一の文字列パラメータで呼び出すことを意図しています。 +代わりに配列を渡すように、greeterの呼び出しを変更してみましょう: ```ts twoslash // @errors: 2345 @@ -83,24 +83,24 @@ let user = [0, 1, 2]; document.body.textContent = greeter(user); ``` -Re-compiling, you'll now see an error: +再コンパイルすると、エラーが表示されます: ```shell error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'. ``` -Similarly, try removing all the arguments to the greeter call. -TypeScript will let you know that you have called this function with an unexpected number of parameters. -In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide. +同様に、greeter関数の呼び出しに渡す引数をすべて削除してみてください。 +TypeScriptは、予期しない数のパラメータを使ってこの関数を呼び出したことを知らせてくれます。 +どちらの場合も、TypeScriptはコードの構造と提供された型注釈に基づいた静的解析を行うことができます。 -Notice that although there were errors, the `greeter.js` file is still created. -You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected. +エラーがあったにもかかわらず`greeter.js`ファイルが生成されたことに注意してください。 +コード中にエラーがあってもTypeScriptを使用することはできます。しかし、その場合は、TypeScriptは期待通りに動作しない可能性が高いことを警告しています。 -## Interfaces +## インターフェース -Let's develop our sample further. Here we use an interface that describes objects that have a firstName and lastName field. -In TypeScript, two types are compatible if their internal structure is compatible. -This allows us to implement an interface just by having the shape the interface requires, without an explicit `implements` clause. +サンプルをさらに発展させましょう。ここでは、firstNameとlastNameフィールドをもつオブジェクトを記述するインターフェースを使用します。 +TypeScript では、2つの型の内部構造に互換性があれば、それらの型は互換性があるとみなされます。 +このことにより、明示的な`implements`句がなくても、インターフェースが必要とする形状を持つだけで、インターフェースを実装することができます。 ```ts twoslash interface Person { @@ -117,15 +117,15 @@ let user = { firstName: "Jane", lastName: "User" }; document.body.textContent = greeter(user); ``` -## Classes +## クラス -Finally, let's extend the example one last time with classes. -TypeScript supports new features in JavaScript, like support for class-based object-oriented programming. +最後に、クラスを使ってこの例をもう一度だけ拡張してみましょう。 +TypeScriptは、クラスベースのオブジェクト指向プログラミングなど、JavaScriptの新しい機能をサポートしています。 -Here we're going to create a `Student` class with a constructor and a few public fields. -Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction. +ここでは、コンストラクタといくつかのpublicフィールドをもつ`Student`クラスを作成します。 +クラスとインターフェースがうまく連携し、プログラマーが適切な抽象度を決定できるようになっていることに注目してください。 -Also of note, the use of `public` on arguments to the constructor is a shorthand that allows us to automatically create properties with that name. +また、コンストラクタの引数に`public`を使うことが、その名前のプロパティを自動的に作成する省略表現になっていることにも注意してください。 ```ts twoslash class Student { @@ -153,12 +153,12 @@ let user = new Student("Jane", "M.", "User"); document.body.textContent = greeter(user); ``` -Re-run `tsc greeter.ts` and you'll see the generated JavaScript is the same as the earlier code. -Classes in TypeScript are just a shorthand for the same prototype-based OO that is frequently used in JavaScript. +`tsc greeter.ts`を再実行すると、生成されたJavaScriptが前述のコードと同じであることが確認できます。 +TypeScriptのクラスは、JavaScriptで頻繁に使われているプロトタイプベースのオブジェクト指向プログラミングの単なる省略表現にしかすぎません。 -## Running your TypeScript web app +## TypeScript の Web アプリを実行 -Now type the following in `greeter.html`: +`greeter.html`に次のように入力してください: ```html @@ -172,16 +172,16 @@ Now type the following in `greeter.html`: ``` -Open `greeter.html` in the browser to run your first simple TypeScript web application! +ブラウザで`greeter.html`を開いて、あなたにとって初めてのシンプルなTypeScriptのWebアプリケーションを実行してみましょう! -Optional: Open `greeter.ts` in Visual Studio, or copy the code into the TypeScript playground. -You can hover over identifiers to see their types. -Notice that in some cases these types are inferred automatically for you. -Re-type the last line, and see completion lists and parameter help based on the types of the DOM elements. -Put your cursor on the reference to the greeter function, and hit F12 to go to its definition. -Notice, too, that you can right-click on a symbol and use refactoring to rename it. +任意: `greeter.ts`をVisual Studioで開くか、TypeScriptプレイグラウンドにコードをコピーしてください。 +識別子にマウスをホバーすると、その型が表示されます。 +型が自動的に推測されているケースもあることに注目してください。 +最後の行を再入力すると、DOM要素の型に基づいた補完リストとパラメータのヘルプが表示されます。 +greeter関数の参照にマウスを置いて、F12を押せば、関数の定義に移動します。 +シンボルを右クリックして、名前を変更するリファクタリングツールを使うことができることにも注目してください。 -The type information provided works together with the tools to work with JavaScript at application scale. -For more examples of what's possible in TypeScript, see the Samples section of the website. +提供された型情報は、アプリケーションの規模でJavaScriptを操作するツールと連携して動作します。 +TypeScriptで可能なことのその他の例ついては、Webサイトのサンプルセクションを参照してください。 ![Visual Studio picture](/images/docs/greet_person.png) From 57a0824e11d01f743e8634e4d6a96c10d8d49ea7 Mon Sep 17 00:00:00 2001 From: uraway Date: Tue, 2 Feb 2021 19:30:30 +0900 Subject: [PATCH 3/4] Apply suggestions from code review Co-authored-by: Daiki Ihara --- docs/documentation/ja/tutorials/DOM Manipulation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/documentation/ja/tutorials/DOM Manipulation.md b/docs/documentation/ja/tutorials/DOM Manipulation.md index 6fcc7170..13d8fd89 100755 --- a/docs/documentation/ja/tutorials/DOM Manipulation.md +++ b/docs/documentation/ja/tutorials/DOM Manipulation.md @@ -100,7 +100,7 @@ interface HTMLElementTagNameMap { 固有のプロパティを持たない要素は`HTMLElement`を返すだけですが、そうでない型は、(`HTMLElement`を拡張あるいは実装した)特定のインターフェースを返します。 -さて、`createElement`定義の残りの部分、`(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]`についてですが、第一引数 `tagName`はジェネリクスパラメータ`K`として定義されています。TypeScriptのインタープリタは、十分に精度が高いのでこの引数からジェネリクスパラメータを _推測_ することができます。開発者がこのメソッドを使うときには、実際にはジェネリクスパラメータを指定する必要がない、ということです。`tagName`引数に渡された値がなんであれ、`K`として推測され、定義の残りの部分を通してずっと使用することができます。その結果次のようなことが起こります。戻り値`HTMLElementTagNameMap[K]`は`tagName`引数を取り、それを使って対応する型を返します。この定義によって、前述のコードスニペットの`p`変数は`HTMLParagraphElement`型を取得します。また、もしコードが`document.createElement('a')`であったならば、`HTMLAnchorElement`型の要素となっていました。 +さて、`createElement`定義の残りの部分、`(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]`についてですが、第一引数 `tagName`はジェネリクスパラメータ`K`として定義されています。TypeScriptのインタープリタは、賢いのでこの引数からジェネリクスパラメータを _推論_ することができます。開発者がこのメソッドを使うときには、実際にはジェネリクスパラメータを指定する必要がない、ということです。`tagName`引数に渡された値がなんであれ、`K`として推測され、定義の残りの部分を通してずっと使用することができます。その結果次のようなことが起こります。戻り値`HTMLElementTagNameMap[K]`は`tagName`引数を取り、それを使って対応する型を返します。この定義によって、前述のコードスニペットの`p`変数は`HTMLParagraphElement`型を取得します。また、もしコードが`document.createElement('a')`であったならば、`HTMLAnchorElement`型の要素を返します。 ## `Node`インターフェース From 7df96cfe10d8703b1e717578ec2d22afc3d857d2 Mon Sep 17 00:00:00 2001 From: uraway Date: Wed, 10 Feb 2021 14:12:07 +0900 Subject: [PATCH 4/4] Apply suggestions from code review Co-authored-by: Daiki Ihara --- docs/documentation/ja/tutorials/Migrating from JavaScript.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/documentation/ja/tutorials/Migrating from JavaScript.md b/docs/documentation/ja/tutorials/Migrating from JavaScript.md index d8bdafe9..7ebba6ad 100644 --- a/docs/documentation/ja/tutorials/Migrating from JavaScript.md +++ b/docs/documentation/ja/tutorials/Migrating from JavaScript.md @@ -152,7 +152,7 @@ TypeScriptサポートがあるエディタでファイルを開く(あるいは これが手抜きだと思うならば、このふるまいを厳しくすることができます。 例えば、エラーがあるときはTypeScriptにJavaScriptへのコンパイルを _させたくない_ 場合、`noEmitOnError`オプションを使うことができます。 -そうした意味では、TypeScriptには厳しさの調整つまみがあり、そのつまみを好きなだけ強くすることができると言えます。 +そうした意味では、TypeScriptには厳しさの段階があり、そのつまみを好きなだけ強くすることができると言えます。 もし利用可能なより厳しい設定を使用するつもりならば、今のうちに設定を有効化しておくのがベストです(後述の[より厳密なチェック](#getting-stricter-checks)を確認してください)。 例えば、明示的に指定していない型をTypeScriptが`any`と暗黙的に推測することを望まない場合、ファイルの修正を始める前に`noImplicitAny`を使いましょう。