Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ja translation] docs/tutorials/* #25

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

uraway
Copy link
Contributor

@uraway uraway commented Feb 1, 2021

@github-actions
Copy link
Contributor

github-actions bot commented Feb 1, 2021

Thanks for the PR!

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

@github-actions
Copy link
Contributor

github-actions bot commented Feb 1, 2021

Translation of TypeScript Tooling in 5 minutes.md

title: 5-minute TypeScript tool
layout: docs
permalink: /ja/docs/handbook/typescript-tooling-in-5-minutes.html
oneline: Tutorial to understand how to make a small website in TypeScript

translatable: true

Let's start by creating a simple web application using TypeScript.

Install TypeScript

There are two main ways to make TypeScript available in your project:

  • Use npm (Node.js package manager)
  • Install typescript Visual Studio plugin

Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default.
Even if you didn't install TypeScript in Visual Studio,downloadis possible.

If you want to use npm, click here:

> npm install -g typescript

Create your first TypeScript file

In the editorgreeter.tsEnter the following JavaScript code in the file:

// @noImplicitAny: false
function greeter(person) {
  return "Hello, " + person;
}

let user = "Jane User";

document.body.textContent = greeter(user);

Compiling code

Above.tsI used an extension, but the code is just JavaScript.
You can also copy/paste from existing JavaScript apps as is.

On the command line, run the TypeScript compiler:

tsc greeter.ts

The result included the same as the JavaScript I just entered.greeter.jsIt will be a file.
In other words, I'm running TypeScript on a JavaScript app!

Now you can take advantage of the new tools that TypeScript offers.
For the function argument 'person', as shown below: stringLet's type annotate:

function greeter(person: string) {
  return "Hello, " + person;
}

let user = "Jane User";

document.body.textContent = greeter(user);

Type annotations

TypeScript type annotations are a lightweight way to record intentional constraints on functions and variables.
This example is intended to call the greeter function with a single string parameter.
Let's change the greeter call so that we pass an array instead:

// @errors: 2345
function greeter(person: string) {
  return "Hello, " + person;
}

let user = [0, 1, 2];

document.body.textContent = greeter(user);

When I recompile, I get an error:

error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

Similarly, try removing all arguments you pass to the greeter function call.
TypeScript lets you know that you called this function with an unexpected number of parameters.
In both cases, TypeScript can perform static analysis based on the structure of the code and the type annotations provided.

Despite the errorgreeter.jsNote that the file was generated.
You can still use TypeScript even if there are errors in your code. However, in that case, typeScript warns that it is likely not to work as expected.

interface

Let's further develop the sample. This section uses an interface that describes objects with firstName and lastName fields.
TypeScript assumes that if the internal structure of two types is compatible, they are considered compatible.
This allows explicitimplementsEven without clauses, you can implement an interface with only the shape that the interface requires.

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

class

Finally, let's extend this example only once again using a class.
TypeScript supports new features of JavaScript, such as class-based object-oriented programming.

Here we have a constructor and some public fieldsStudentCreate a class.
Notice that classes and interfaces work well together to help programmers determine the appropriate level of abstraction.

In addition, the constructor's argumentspublicNote that using is an abbreviation that automatically creates properties for that name.

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

tsc greeter.tsIf you rerun , you can see that the generated JavaScript is the same as the code above.
TypeScript classes are just abbreviations of prototype-based object-oriented programming that is frequently used in JavaScript.

Run typescript web apps

greeter.htmlType:

<!DOCTYPE html>
<html>
  <head>
    <title>TypeScript Greeter</title>
  </head>
  <body>
    <script src="greeter.js"></script>
  </body>
</html>

In the browsergreeter.htmlOpen and run a simple TypeScript web application for you first time!

arbitrary: greeter.tsopen in Visual Studio or copy the code to TypeScript Playground.
Hovering the mouse over the identifier displays its type.
Notice that in some cases the type is automatically guessed.
Re-entering the last line will provide help for completion lists and parameters based on the type of the DOM element.
Hover over the greeter function reference and press F12 to go to the function definition.
Notice also that you can right-click on a symbol and use a refactoring tool to rename it.

The provided type information works in conjunction with tools that work with JavaScript at the size of the application.
For other examples of what typescript can do, see the sample section of the website.

Visual Studio picture

Translation of React.md

title: React
layout: docs
permalink: /ja/docs/handbook/react.html
oneline: Links to learn about TypeScript and React

translatable: true

TypeScript isJSXsupports,useStatePatterns used in react codebases such as can be modeled correctly.

React project setup

Nowadays, there are a lot of frameworks that support TypeScript as standard:

All of this is a great framework as the first step in the project.This websiteTypeScript andGatsbyand this will also be a useful implementation reference.

document

Here are some of the best sources to stay up to date on React and TypeScript:

Translation of Migrating from JavaScript.md

title: Migrating from JavaScript
layout: docs
permalink: /ja/docs/handbook/migrating-from-javascript.html

oneline: How to migrate from JavaScript to TypeScript

TypeScript doesn't exist on its own.
Built with the JavaScript ecosystem in mind, there are a lot of JavaScripts out there today.
Migrating your JavaScript codebase to TypeScript can be a bit cumbersome, but it's usually not difficult.
In this tutorial, we'll look at how to get started with the migration.
It is assumed that you have fully loaded the handbook for writing new TypeScript code.

If you're thinking of migrating in a React project, start withReact Conversion GuideWe recommend that you read the .

Directory settings

If you are writing javascript, it is likely that you are running JavaScript directly.
In this case.jsThe file issrclibordistIt will be located in a directory and running as needed.

In these cases, the written file will be used as input to TypeScript and will execute the output generated by TypeScript.
During the transition from JS to TS, you need to isolate the input file so that TypeScript does not overwrite the input file.
If the output file needs to be placed in a specific directory, it becomes the output directory.

You might bundle it, use another transpilla like Babel, or perform intermediate steps on JavaScript.
In this case, you may have already set up a folder configuration as described above.

Now assume that the directory is configured as follows:

projectRoot
├── src
│   ├── file1.js
│   └── file2.js
├── built
└── tsconfig.json

srcOutside the directorytestsIf you have a folder,srcIntsconfig.jsonI put one,testsYou can also put one in.

Describe the configuration file

TypeScript manages project settings such as which files you want to include and what types of checks you want to performtsconfig.jsonuse a file called .
Let's create a configuration file that is the minimum necessary for the project:

{
  "compilerOptions": {
    "outDir": "./built",
    "allowJs": true,
    "target": "es5"
  },
  "include": ["./src/**/*"]
}

Above, we specify a few points for TypeScript:

  1. srcLoad interpretable files in the directory (includein)
  2. Allow JavaScript files as input files (allowJsin)
  3. builtPrint all output files to the directory (outDirin)
  4. Convert the structure of the new JavaScript to an older version like ECMAScript5 (targetin)

At this point, at the root of the projecttscIf you try to run ,builtYou should be able to see the output file in the directory.
builtThe layout of the files insrcit will look the same as the one.
TypeScript now works in your project.

Benefits of early adoption

Even at this stage, there are some benefits that TypeScript can get from understanding your project.
VS CodeandVisual StudioIf you open an editor like , you'll see that you'll often get support from tools like Completion.
You can also find specific bugs by setting options such as:

  • noImplicitReturnsprevents you from forgetting to set the last return value of the function.
  • noFallthroughCasesInSwitchisswitchOf the blockcasebetweenbreakThis is useful when you don't want to forget a sentence.

TypeScript also warns you of unreachable code and labels. Each of these warningsallowUnreachableCodeandallowUnusedLabelsyou can turn it off.

Integration with build tools

There may be more build steps in the pipeline.
Maybe you've concatenated some other files to each file.
Each has a different build tool, but we'll cover the gist of it as much as possible.

Gulp

If you're using Gulp in any way, typescript andUsing Gulpand tutorials on integration with common build tools like Browserify, Babelify, and Uglify.
For details, please check there.

Webpack

Integration with Webpack is very simple.
TypeScript is a loaderts-loaderand make debugging easier.source-map-loaderCan be combined.
Run the following command:

npm install ts-loader source-map-loader

And the following optionswebpack.config.jsMerge into files:

module.exports = {
  entry: "./src/index.ts",
  output: {
    filename: "./dist/bundle.js",
  },

  // webpack の出力をデバッグするためのソースマップを有効にします。
  devtool: "source-map",

  resolve: {
    // 解決可能な拡張子として'.ts'と'.tsx'を追加します。
    extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
  },

  module: {
    rules: [
      // '.ts'または'.tsx'拡張子を持つすべてのファイルは'ts-loader'によって処理されます。
      { test: /\.tsx?$/, loader: "ts-loader" },

      // 出力されるすべての'.js'ファイルは'source-map-loader'によって再処理されたソースマップを持ちます。
      { test: /\.js$/, loader: "source-map-loader" },
    ],
  },

  // その他のオプション...
};

Importantly,.jsIt is a point that ts-loader must be executed before any other loader dealing with the file.

Another TypeScript loader in Webpackawesome-typescript-loaderBut the same is true.
For the difference between the two,HereSee .

An example of using Webpack is:React and Webpack tutorialsYou can check it in.

Migrate to TypeScript files

By now, you're ready to start using typescript files.
The first step in the migration is to.jsThe file.tsrename it.
If the file is using JSX,.tsxmust be renamed.

Have you finished this step?
This is good!
Now you have successfully migrated files from JavaScript to TypeScript!

Of course, you might think this step is incorrect.
Open a file in an editor with TypeScript support (or tsc --pretty ) and you may see a red squigly on a particular line.
Think of this the same way as the red squig lines in editors like Microsoft Word.
Just as you can print your publication in Word even if you have a red squigly, TypeScript converts the code even if there are red squigly.

If you think this is daft, you can tighten this behavior.
For example, if there is an error, compile to JavaScript in TypeScript I don't want you to let casenoEmitOnErrorYou can use the options.
In that sense, TypeScript has a stage of riginess, and it can be said that the knob can be made as strong as you like.

If you intend to use the more restrictive settings available, it is best to enable them now (see below.Stricter checkscheck the ).)
For example, typeScript can use types that are not explicitly specified.anyand implicitly, before you start modifying the filenoImplicitAnyLet's use.
You may be somewhat confused by the code to fix, but you can get long-term benefits fairly quickly.

Removing errors

As mentioned earlier, it is not unpredictable that you will get an error message after conversion.
The important thing is to actually check for the errors one by one and decide how to deal with them.
In many cases, these are reasonable bugs, but sometimes you may have to explain to TypeScript a little better what you're trying to do.

Import from Modules

At firstCannot find name 'require'.andCannot find name 'define'.You may see a lot of errors such as.
In such a case, you are probably using a module.
To convince TypeScript that these calls exist, you can code the following or

// Node/CommonJS用
declare function require(path: string): any;

Or code like this:

// RequireJS/AMD用
declare function define(...args: any[]): any;

You could write , but it's better to remove these calls and use typescript syntax for import.

First, typescriptmoduleYou must flag it to enable the module system.
The available options are:commonjsamdsystemAndumdare.

Node/CommonJS code such as:

var foo = require("foo");

foo.doStuff();

Or suppose you have a RequireJS/AMD code like this:

define(["foo"], function (foo) {
  foo.doStuff();
});

In that case, you would write TypeScript code like this:

import foo = require("foo");

foo.doStuff();

Retrieving declaration files

If you start converting to TypeScript import, you probablyCannot find module 'foo'.you will encounter such an error.
The problem here is that you can write a library Declaration file is not to have.
Fortunately, this is very easy to solve.
TypeScriptlodashIf you're complaining about a package like this, you just have to write something like this:

npm install -S @types/lodash

IfcommonjsIf you are using a module option other thanmoduleResolutionOptionallynodeYou will need to set it up.

Now you can import the lodash without any problems to get the exact completion.

Export from module

Typically, exporting from a module isexportsandmodule.exportsrequires adding properties to values such as .
TypeScript allows you to use top-level export declarations.
For example, let's say you export a function that looks like this:

module.exports.feedPets = function (pets) {
  // ...
};

This can also be written as follows:

export function feedPets(pets) {
  // ...
}

Sometimes I completely overwrite the exports object.
This is a common pattern to create modules that can be called immediately, such as the following snippet:

var express = require("express");
var app = express();

Previously, you might have written:

function foo() {
  // ...
}
module.exports = foo;

In TypeScript,export =It can be modeled in a structure.

function foo() {
  // ...
}
export = foo;

Arguments that are too/too little

Sometimes you notice that you are calling a function with too many/too few arguments.
Usually, this is a bug, but in some cases instead of describing parametersargumentsYou may be declaring a function that uses an object.

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, you can use the overload of the functionmyCoolFunctionYou need to use TypeScript to tell the caller how you can call .

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];
    // ...
  }
  // ...
}

Two overload signaturesmyCoolFunctionI added it to.
The first function signature ismyCoolFunctionThere is (number) function, and thennumberindicates that you will receive a list of .
The second takes a function as well, and the rest parameter (...nums) to any number of subsequent argumentsnumberindicates that it must be.

Properties added sequentially

Some people find it more aesthetic to create an object and add properties immediately after:

var options = {};
options.color = "red";
options.volume = 11;

TypeScript isoptionsType has no properties{}because I first understood ascolorandvolumeyou'll say you can't assign.
Moving the property declaration into the object literal does not cause an error:

let options = {
  color: "red",
  volume: 11,
};

AlsooptionsYou can define types to add type assertions to object literals.

interface Options {
  color: string;
  volume: number;
}

let options = {} as Options;
options.color = "red";
options.volume = 11;

oroptionsisanyYou can also specify that it is a type. This is the easiest way, but with the least benefits.

anyObjectAnd{}

Objectis the most common type in most cases, so to make the value have any type,Objectand{}You may want to use .
However, in such a case, anyThe type you really want to useare. Because this is the most flexible Because it is a type.

For instanceObjectAnd the ones that are typed,toLowerCase()You cannot call a method like .
Being a more general type usually means that there is less you can do with a type.anyis special in that it is the most common type, but you can do anything.
This means that you can call, use it as a constructor, access properties, and so on.
howeveranyKeep in mind that you always lose the error checking and editor support provided by TypeScript.

IfObjector{}When you choose{}You should choose.
The two are almost identical, but in certain esoteric cases{}ThanObjectIt is a more technically common type.

Stricter checks

TypeScript provides a check function to increase safety and improve program analysis.
Once you've converted your codebase to TypeScript, you can enable these checks for added safety.

ImplicitanyBan

Sometimes TypeScript doesn't understand what some type is.
To make type choices as loose as possible, TypeScript insteadanyyou will be using.
This decision is great in terms of moving to TypeScript.anymeans that you don't get type secure, and you don't get any other tool support.
noImplicitAnyto mark TypeScript and give an error.

exactnullandundefinedcheck

By default, TypeScriptnullandundefinedis in any type area.
What you meannumberAnything declared by typenullandundefinedthere is a possibility that it will be.
nullandundefinedis a frequent source of bugs in JavaScript and TypeScript, so TypeScriptstrictNullChecksOptions reduce the stress of worrying about these problems.

strictNullChecksWhen is enabled,nullandundefinedEach of themnullandundefinedGet your own type.
If some value isnullChiaki There's a possibility. You can always use the Union type with the original type.
For example, if a value isnumberandnullif there is a possibility that the type isnumber | nullWrite.

If TypeScriptnull/undefinedsuffix if you know that there is no possibility that even if there is a value that you believe there is a possibility of!You can use the operator to tell you that.

declare var foo: string[] | null;

foo.length; // エラー - 'foo'は'null'の可能性があります

foo!.length; // OK - 'foo!'は'string[]'型だけです

As a caveat,strictNullChecksIf you use, do the samestrictNullChecksYou may need to update your dependencies to use .

thisimplicit againstanyBan

Outside the classthisIf you use keywords, by defaultanyIt becomes a type.
For instancePointLet's say you have a class and you have a function that you want to add as a method:

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);
  }
}
// ...

// インターフェースを再定義する
interface Point {
  distanceFromOrigin(): number;
}
Point.prototype.distanceFromOrigin = function () {
  return this.getDistance({ x: 0, y: 0 });
};

It has the same problem as the one mentioned earlier - getDistanceyou may misspell the , and you will not get an error.
For this reason, TypeScript includes:noImplicitThisThere are options.
If this option is set, TypeScript willthisif it is used without an explicit (or inferred) type, an error is issued.
To fix it, clickthisIt uses parameters to give explicit types within the interface or function itself.

Point.prototype.distanceFromOrigin = function (this: Point) {
  return this.getDistance({ x: 0, y: 0 });
};
Translation of DOM Manipulation.md

title: Working with the DOM
layout: docs
permalink: /ja/docs/handbook/dom-manipulation.html
oneline: Working with DOM in TypeScript

translatable: true

Working with the DOM

HTMLElementExploring types

Over the more than 20 years since it was standardized, JavaScript has come a very long way. In 2020, JavaScript will now be available on servers, in data science, and even IoT devices, but it's important to remember about the most common use cases: web browsers.

A website consists of HTML and XML documents. These documents are static and unchanged.Document Object Model (DOM) is a programming interface implemented by the browser to make static websites functional. The DOM API can be used to modify the structure, style, and content of documents. The API is so powerful that countless front-end frameworks (jQuery, React, Angular, etc.) have been developed to make it easy to create dynamic websites.

TypeScript is a typed superset of JavaScript that provides type definitions for the DOM API. These definitions are readily available in all default TypeScript projects. More than 20,000 lines lib.dom.d.ts some of the definitions in are particularly prominent. Well in factHTMLElementare. This type is the basis of DOM manipulation in TypeScript.

DOM type definitionYou can examine the source code of

Basic examples

Simplified as follows index.html Suppose you have a file:

<!DOCTYPE html>
<html lang="en">
  <head><title>TypeScript Dom Manipulation</title></head>
  <body>
    <div id="app"></div>
    <!-- Assume index.js is the compiled output of index.ts -->
    <script src="index.js"></script>
  </body>
</html>

#appTo the element<p>Hello, World</p>Let's take a look at a TypeScript script that adds elements.

// 1. idプロパティを使ってdiv要素を選択します
const app = document.getElementById("app");

// 2. プログラムによって新しい<p></p>要素を作成します
const p = document.createElement("p");

// 3. テキストの内容を追加します
p.textContent = "Hello, World!";

// 4. p要素をdiv要素に追加します
app?.appendChild(p);

Compile and index.html When you open the page, the HTML will result in:

<div id="app">
  <p>Hello, World!</p>
</div>

Documentinterface

In the first line of TypeScript, global variablesdocumentI'm using . If you look at this variable,lib.dom.d.ts In the fileDocumentYou can see that it is defined in the interface. The code snippet includes:getElementByIdandcreateElementContains calls to two methods.

Document.getElementById

The definition of this method is as follows:

getElementById(elementId: string): HTMLElement | null;

Pass the id string of the element,HTMLElementornullreturns . This method is one of the most important typesHTMLElementis guided. This type serves as the underlying interface for all other elements. For example, the variables in the code example abovepisHTMLParagraphElementType. In addition, this methodnullmay return . This is because we cannot guarantee that the specified element can actually be found before this method is executed. In the last line of the code snippet,appendChildTo call the new feature, Optional Chaining Operator is used.

Document.createElement

The definition of this method is as follows (Deprecated Definition omitted):

createElement<K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];
createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;

The definition of this function is overloaded. The second overload is the simplest,getElementByIdbehaves very similar to Anystringreturns the standard HTMLElement. This definition allows developers to create tags for unique HTML elements.

For instancedocument.createElement('xyz')Is<xyz></xyz>return an element, but this is clearly not the element specified in the HTML specification.

If you are interested,document.getElementsByTagNameTry touching custom tag elements with

createElementThe first definition of uses multiple advanced generic patterns. It is best to understand this in chunks. First of all, the generic type<K extends keyof HTMLElementTagNameMap>I'll look at it from. This expression isHTMLElementTagNameMapOn the key of Restricted Generix parametersKis defined. The map interface contains all the HTML tag names specified and all the corresponding type interfaces. For example, the first five mapped values are:

interface HTMLElementTagNameMap {
    "a": HTMLAnchorElement;
    "abbr": HTMLElement;
    "address": HTMLElement;
    "applet": HTMLAppletElement;
    "area": HTMLAreaElement;
        ...
}

Elements that do not have unique propertiesHTMLElement, but the type that does not is (HTMLElement(extended or implemented) returns a specific interface.

wellcreateElementThe rest of the definition,(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]is about but the first argument tagNameis a generic parameterKit is defined as . TypeScript interpreters are clever, so we can use this argument to inference You can. When developers use this method, they don't actually need to specify generic parameters.tagNameWhatever the value passed to the argument,Kcan be used throughout the rest of the definition. As a result, the following occurs: Return valueHTMLElementTagNameMap[K]IstagNameTake an argument and use it to return the corresponding type. This definition allows you to use the code snippets described above.pThe variable isHTMLParagraphElementGets the type. Also, if the code isdocument.createElement('a')If it was,HTMLAnchorElementReturns an element of a type.

Nodeinterface

document.getElementByIdThe function isHTMLElementreturns .HTMLElementisNodeThe interface has been extended.ElementAn extension of the interface. With the extension of this prototype, allHTMLElementscan take advantage of a subset of standard methods. In the code snippet above,NodeNew with the properties defined in the interfacepadding elements to the website.

Node.appendChild

The last line of the code snippet isapp?.appendChild(p)are. aforementioneddocument.getElementByIdSection of , at run time,appso here's because there could be null Optional Chaining I explained that we use operators.appendChildis defined as follows:

appendChild<T extends Node>(newChild: T): T;

This method iscreateElementWorks like a method and has generic parametersTIs newChildInferred from arguments.Tis another base interfaceNodeat restriction Has been.

childrenandchildNodesThe difference between

In the previous section,HTMLElementThe interface isNodeExtendedElementI explained that it is an extension of . The DOM API includes:child there are elements, for example, in the following HTML,pThe tag isdivThe child of the element.

<div>
  <p>Hello, World</p>
  <p>TypeScript!</p>
</div>;

const div = document.getElementsByTagName("div")[0];

div.children;
// HTMLCollection(2) [p, p]

div.childNodes;
// NodeList(2) [p, p]

divAfter you get the element,childrenThe property isHTMLParagraphElementsIs a list that containsHTMLCollectionreturns .childNodesThe property is a list of similar nodesNodeListreturns . EachpThe tag isHTMLParagraphElementsIt remains a type,NodeListIsHTMLCollectionNot on the list HTML node can be included.

The text remains unchanged and onepLet's remove the tag and change the HTML.

<div>
  <p>Hello, World</p>
  TypeScript!
</div>;

const div = document.getElementsByTagName("div")[0];

div.children;
// HTMLCollection(1) [p]

div.childNodes;
// NodeList(2) [p, text]

Let's see how both lists change.childrenin order to<p>Hello, World</p>only elements are included.childNodesThere are twopInstead of nodes,textNodes are now included.NodeListoftextThe part of is the text TypeScript!Literals includingNodeare. ThisNodeIsHTMLElementbecause it is not consideredchildrenIt is not included in the list.

querySelectorandquerySelectorAllmethod

Both of these methods are great tools for retrieving a list of DOM elements that fit more unique constraints.lib.dom.d.ts In , it is defined as follows:

/**
 * セレクタにマッチするノードの子孫である最初の要素を返します。
 */
querySelector<K extends keyof HTMLElementTagNameMap>(selectors: K): HTMLElementTagNameMap[K] | null;
querySelector<K extends keyof SVGElementTagNameMap>(selectors: K): SVGElementTagNameMap[K] | null;
querySelector<E extends Element = Element>(selectors: string): E | null;

/**
 * セレクタにマッチするノードの子孫であるすべての要素を返します。
 */
querySelectorAll<K extends keyof HTMLElementTagNameMap>(selectors: K): NodeListOf<HTMLElementTagNameMap[K]>;
querySelectorAll<K extends keyof SVGElementTagNameMap>(selectors: K): NodeListOf<SVGElementTagNameMap[K]>;
querySelectorAll<E extends Element = Element>(selectors: string): NodeListOf<E>;

querySelectorAllThe definition of the new typeNodeListOfexcept that it returns getElementsByTagNameIt is similar to . This return type is basically a custom implementation of standard JavaScript list elements. First of all, without a doubt,NodeListOf<E>ToE[]you'll get a very similar user experience.NodeListOfislengthitem(index)forEach((value, key, parent) => void)implement only properties and methods, such as numeric indexes. In addition, this methodNodeListBut.childNodesI was returning from the method Chi-Yu Not_element_ Returns a list of . This may seem contradictory.ElementIf the interfaceNoderecall that it is an extension of .

To see the above method in action, let's modify the existing code as follows:

<ul>
  <li>First :)</li>
  <li>Second!</li>
  <li>Third times a charm.</li>
</ul>;

const first = document.querySelector("li"); // 最初のli要素を返す
const all = document.querySelectorAll("li"); // すべてのli要素のリストを返す

Want to know more?

lib.dom.d.ts The best thing about type definitions in is that they reflect the types annotated on the Mozilla Developer Network (MDN) documentation site. For instanceHTMLElementIsHTMLElement pageit can be found in the . These pages list all available properties, methods, and sometimes even examples. Another great thing about these pages is that they have links to the corresponding standard documentation. The above page includes:HTMLElement's W3C RecommendationThere is a link.

data:

Translation of Babel with TypeScript.md

title: Use Babel in TypeScript
layout: docs
permalink: /ja/docs/handbook/babel-with-typescript.html
oneline: How to create a project that combines Babel and TypeScript

translatable: true

Babel and TypeScripttscComparison of

When creating a modern JavaScript project, what is the right way to transpile files from TypeScript to JavaScript?

The answer is that the project "Depending on the situation" Or, "Someone decided" It is often.tsdxAngularNestJSexisting frameworks, orGetting StartedIf you're building a project using a framework like the one shown in , they'll make this decision for you.

On the other hand, useful rules of thumb include:

  • Is the build output almost the same as the source input file? And nowtscLet's use
  • Need a build pipeline that can have multiple outputs? So, the transpilebabelto type checktscLet's use

Babel for Transpile, for Moldtsc

Here are the patterns common in projects with existing build infrastructure that may have been ported to TypeScript from the JavaScript codebase.

This technique is used by Babelpreset-typescriptto generate JS files, and then typescript to check and.d.tsIt's a hybrid approach to generating files.

Babel's TypeScript support allows it to work with existing build pipelines, and Babel doesn't type-check the code, which increases the likelihood of reducing js output time.

Type checking and d.ts file generation

A disadvantage of using Babel is that you may not be able to get type checking when transpile from TS to JS. This means that type errors that you missed in the editor may slip into production code.

In addition, Babel is for TypeScript.d.tsBecause you can't generate a file, it can be difficult to work with that library if your project is a library.

To solve these problems, you need to set up a command to type-check your project using TSC. This probably corresponds to some of Babel's settingstsconfig.jsonyou will want to make sure that the following flags are enabled:

"compilerOptions": {
  // tscによって.d.tsファイルを作成させますが、.jsファイルは作成されないようにします
  "declaration": true,
  "emitDeclarationOnly": true,
  // BabelがTypeScriptプロジェクト内のファイルを安全にトランスパイルできるようにします
  "isolatedModules": true
}

Learn more about the flags above:

Generated by 🚫 dangerJS against 7df96cf

Copy link

@sasurau4 sasurau4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

お待たせしました 🙏

@uraway
Copy link
Contributor Author

uraway commented Feb 10, 2021

ありがとうございます!

Copy link

@sasurau4 sasurau4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍

@uraway uraway closed this Dec 23, 2021
@uraway uraway reopened this Dec 23, 2021
@uraway
Copy link
Contributor Author

uraway commented Dec 23, 2021

LGTM

https://github.com/microsoft/TypeScript-Website-Localizations/runs/4617288333?check_suite_focus=true

Running version 1.6.0


Looking at the issue_comment from uraway in '[ja translation] docs/tutorials/*' to see if we can proceed
Changed files: 
 - /docs/documentation/ja/tutorials/Babel with TypeScript.md
 - /docs/documentation/ja/tutorials/DOM Manipulation.md
 - /docs/documentation/ja/tutorials/Migrating from JavaScript.md
 - /docs/documentation/ja/tutorials/React.md
 - /docs/documentation/ja/tutorials/TypeScript Tooling in 5 minutes.md
Creating comments and merging
Merging (or commenting) failed:
Error: HttpError: Resource not accessible by integration
Error: Failed to merge

@github-actions
Copy link
Contributor

There was an issue merging, maybe try again uraway. Details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants