2020年6月19日金曜日

TypeScriptの背景には、偉大な考えがあった。There was a great idea behind TypeScript.

https://postd.cc/i-was-wrong-about-typescript-here-is-why/

シェアしました。

私がTypeScriptについて勘違いしていたこと、そしてその理由




(訳注:2016/9/28、頂きましたフィードバックを元に記事を修正いたしました。)
何か新しいものが登場したと聞くと、人はそれに対する賛否を選ぶ傾向があります。TypeScriptが登場したときの私は、キーコンセプトのうち自分に合わないものをほんの幾つか取り上げて「否」の側を選んでしまいました。この記事では、私が当時どのように考えていたか、そして私がどのようにして「TypeScriptの背景には、大きな犠牲なしに利点を得る方法を知る人々による偉大な考えがあった」ことに気付いたかを説明しようと思います。

TypeScriptが登場したときの私の考え

Anders Hejlsbergが何かに取り組んでいるときは、つい私はそちらに注意を完全に傾けてしまいます。彼はコンパイラの構築やプログラミング言語の設計を30年近く経験してきています。彼の様々なプログラミング言語に関する貢献については彼のWikipediaのページでもっと読むことができます。
「彼がJavaScriptにトランスパイル(つまり、ソースコードからソースコードへのコンパイル)される言語に取り組んでいる」と聞いた時、私の第一印象は失望でした。MicrosoftはDart/CoffeeScriptの道をたどり、ECMAScriptの標準の道を拒んだのだと。私は何かを短く書くためだけに、新しい言語を学んでこれまで学んだことを忘れてしまうようなことはしません。もっとメリットがないと、そうする理由がありません。
また、Microsoftの「ASP.NET Webフォームを導入することでWindowsの開発者をWeb開発に取り込もうとした」というやり方について、私には悪い思い出もありました。Webフォームは、Webの中核となる技術を、混在した結果とともに抽象化してしまいました。「TypeScriptは、JavaScriptを”学べない”C#開発者を対象にしたものなのではないか?」「新しい言語は、C#の開発者が使い慣れた機能を持つものになるのではないか?」
Hejlsbergがチームにいてさえも、私はTypeScriptに単純に歓喜することはできず、それ以上深く探ることはしませんでした。その言語とコンパイラに関するいくつかのキーポイントを完全に見落としていたのです。

TypeScriptのメリットを今すぐ得る

最近のクライアントのプロジェクトで、TypeScriptがReactReduxと共に使われていました。ReactとReduxは共に私にはなじみがあるもので、モダンなJavaScript (ECMAScript 2016, ES6) も6か月ほど書いていました。
TypeScriptを始める方法の一つは、お気に入りのエディタを一つ選び(例えばVisual Studio CodeSublime Text、あるいはAtom)、そこからTypeScriptのコンパイラを実行することです。私はTypeScript Sublime Pluginをインストールし、ネイティブHTML要素での幾つかの自動補完サジェストを試しました。

技術的な注記:テキストエディタのプラグインは、TypeScriptコンパイラのAPIの一部であるLanguage Serviceを利用します。これは、開発者にとって低レイテンシでのフィードバックが重要である場合のテキスト編集のために設計されています。上記のアニメーションの例のgetCompletionsAtPositionなど、美しいAPIを提供しています。

TypeScriptとサードパーティのライブラリ

ここまでまだTypeScriptをまったく書いておらず、.ts拡張子を持つES5のソースコードファイルを書いただけです。サードパーティライブラリのAPI記述を入手することで、コンパイラからもっと多くの利点を得られます。API記述をTypeScriptではType Definition(型定義)と呼びます。
有名なViewライブラリであるReactと、その型定義をダウンロードしてみましょう。型定義ファイルは、react.d.tsのように、ファイル名の”d”から判別できます。
型定義を管理するツールはTypingsといいます。
Typingsをインストールするには、npm install typings -gを実行します。
TypingのコマンドラインAPIが馴染みのあるものであることに気付くのではないでしょうか。npmで用いられるものによく似ているのです。
Typingsをインストールした後は、initコマンドを用いて設定ファイルを生成します。 : typings init
searchコマンドを–nameフラグと共に使い、型定義を名前で検索しましょう。
  1. > typings search --name react
  2. Viewing 1 of 1
  3.  
  4. NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED
  5. react dt http://facebook.github.io/react/ 2 2016-05-26T13:46:01.000Z
“dt”は型定義のソースの場所を表します。これは例えば、npmであったり、Definitely Typed(dt)という有名なサイトだったりします。ソースのリストはここで見られます。
型定義はinstallコマンドでインストールできます。
  1. typings install dt~react dt~react-dom --save
–saveフラグはnpmの–saveフラグと似た挙動を持ちます。つまり、型定義の参照を、typings initで生成されたtyping.jsonに保存します。
まだReactそのものをインストールしていませんでしたが、npmでインストールできます。
  1. npm install react react-dom --save
サードパーティのライブラリとその型定義ファイルがある状態での開発とは、一体どのようなものになるのでしょう?私は例として、2つのプロパティを持つReactコンポーネントを作り、それを使ったり編集したりする際に自動補完がどのように動作するかを観察しました。
alt-text
この例では、TypeScriptの最初のスニペットとしてインターフェース宣言を追加しています。私はあらゆる場面で型を追加することに厳格ではありませんが、外部に露出するエントリーポイント(コンポーネントのプロパティなど)を説明することは有益です。

型定義のメリット

これで、APIの定義を覚えたり覗いたりする必要がなくなり、APIを利用するのが簡単になりました。リファクタリングももっと簡単になります。
ここで、他のたくさんのコンポーネント内で使われていて、異なるプロパティが必要なDemoComponentがあると仮定しましょう。例えば、nameプロパティがあり、より特化した他のプロパティ(username, surname, fullNameなど)に変更されうるとします。大きなプロジェクト内で’.name’というキーワードで検索・置換を行うと、端的に言って、あなたは参ってしまうでしょう。正しいコンテキストかどうかについて、検索でヒットしたものをすべてチェックしなければなりません。型が適切な箇所で用いられていれば、nameプロパティはより語義に忠実な意味になり、さらに、ツール側にもリファクタリングで影響される名前がどれであるかわかるようになります。
alt-text
上記のアニメーションで示した例はシンプルですが、大きなコードベースでも同じような操作ができることは容易に想像できるでしょう。

型に関する誤解

“強い型付け”と聞くと、「古い(型インターフェースなど以前の)C#やJavaのコードのように、あらゆる箇所で型が必要になる」と考えられがちです。
  1. IDictionary<int, Car> carsById = new Dictionary<int, Car>();
これでは、利点がないのに多くのノイズがあります。
TypeScriptには型推論という機能があり、以下のように入力するとエラーを吐くように動作します
  1. let name = "tatu"
  2. name = 2; // an error
nameがStringであることが推論されているため、明示的に示す必要がないのです。
また、TypeScriptにはContextual Type(文脈的型付け)という機能があります。以下はドキュメントからの例です。
  1. window.onmousedown = function(mouseEvent) {
  2. console.log(mouseEvent.buton); //<- Error
  3. };
mouseEventには定義された型はありませんが、それでもTypeScriptはmouseEventbuttonというプロパティを持たない場合にエラーを投げることができます。どうしてこれが可能なのでしょう?
それは、TypeScpritが「onmousedownに対するコールバックはMouseEvent型の引数をとる関数である」と知っているからです。MouseEvent型はbuttonプロパティを持ちません。こういったチェックにより、開発者の時間を節約することができます。

TypeScriptを他のツールと共に使う

JavaScriptの開発で使ってきた他のツールについて考えたとき、思い至ったのは以下のものでした:リンティングツール、Browserify/Webpack、テストフレームワーク、そしてBabelJSです。これらのツールは、TypeScriptによって時代遅れになるでしょうか?

lintツール

エラーの捕捉においてTypeScriptがとても強力であれば、果たしてESLintやJSHintなどのツールは必要でしょうか?答えは「Yes」です。例えば、エラーのチェックに加え、ESLintはベストプラクティスや文体といった面でのコードフォーマットのチェックを行えます。残念ながらESLintとの互換性はTypeScript ESLint Parserプロジェクトに依存しており、このプロジェクトはまだ実験段階です。
良いニュースとしては、TypeScriptのために作られたTSLintというツールが存在します。

Browserify/Webpack

TypeScriptはバンドルツールではないため、例えば「自分自身のコードはTypeScriptで書いているが、ブラウザではサードパーティ製ライブラリであるlodashを使っている」というケースで、TypeScriptではlodashをフェッチして1つのファイルにバンドルすることができません。バンドルするのはBrowserify/Webpackの役割になります。

テストフレームワーク

私はTypeScriptでテストを書き、JavaScriptにコンパイルし、テストの実行などのためにMochaを使う、ということをやりました。これに関しての皆さんの意見を聞きたいです。

BabelJS

TypeScriptがES2016の機能のサポートしているということは、BabelJSはもう不要でしょうか?答えは「状況による」です。賢い人に、BabelJSのもたらす利点について尋ねてみました。

著者:「ES2015のコードをトランスパイルするのに、#TypeScript コンパイラではなく#babeljs を使わなければいけない理由を、誰か教えてくれませんか?」
Tero Parviainen:「TypeScriptは今のところasync/awaitをES5にコンパイルできません。もしこれらが必要であればBabel等を使う必要があります」

言い換えれば、TypeScriptはasync/awaitをサポートしているが、それを全ブラウザで理解可能なECMAScriptにコンパイルすることはできません。
この機能を使わないのであれば、ビルドプロセスからBabelJSを消してしまっても構わないのです。
追記:読者のBirk Skyumが指摘してくれたのですが、この機能のES3へのサポートはTypeScriptのロードマップに存在しており、バージョン2.0でリリースされる予定とのことです。

TypeScriptを使うべき時とは

TypeScriptに関するブログ投稿のほとんどは、「TypeScriptは大きなプロジェクトでの使用を企図している」と言及しています。Anders HejlsbergのJavaScript Jabberでのインタビュー(30:50)によると、
もし5行だけのコードを書くのであれば、それはTypeScriptの導入という努力には値しないでしょう…… プロジェクトが大きくなればなるほど、TypeScriptの有用性は上がっていきます。さきに私が述べたように、数千行のコードになるまでには、スラム・ダンク(大成功)になっているでしょう。
* 「スラム・ダンク」がわからず、Google検索しなければなりませんでした。どうやら、外すほうが難しいような簡単なシュートを指すバスケット用語のようです。

結論

願わくば、少なくとも私のTypeScriptへの熱狂が皆さんに伝わり、それで皆さんがTypeScriptにもう一度チャンスを与えるようになれば幸いです。実際のプロジェクトでTypeScriptを使って成功したか、あるいは惨めな経験をしたか、是非お聞きしたいです。それではまた今度!
Discuss on Hacker News

There was a great idea behind TypeScript. There was a great idea behind TypeScript.

https://postd.cc/i-was-wrong-about-typescript-here-is-why/

I shared.

What I misunderstood about TypeScript and why

When
I hear something new comes up, people are more likely to choose for or against it. When TypeScript came along, I picked up a few key concepts that didn't suit me and chose the "no" side. In this article, I found out what I was thinking at that time, and how I had "a great idea in the background of TypeScript by people who knew how to get the benefits without a big sacrifice." I will explain why.

My thoughts when TypeScript appeared

When Anders Hejlsberg is working on something, I'm just completely paying attention to it. He has nearly 30 years of experience building compilers and designing programming languages. You can read more about his contributions to various programming languages ​​on his Wikipedia page .
My first impression was disappointing when I heard, "He's working on a language that is transpiled into JavaScript (ie source code to source code compilation)." Microsoft followed the Dart/CoffeeScript path and rejected the ECMAScript standard path. I don't learn new languages ​​and forget what I have learned, just to write something short. There is no reason to do so without more benefits.
I also had bad memories of Microsoft's approach to "getting Windows developers into Web development by introducing ASP.NET Web Forms." Web forms have abstracted the core technologies of the Web with mixed results. "Isn't TypeScript intended for C# developers who can't learn JavaScript?" "Isn't a new language something that C# developers are used to?"
Hejlsberg said. Even on the team, I simply couldn't rejoice at TypeScript and didn't go deeper into it. I completely missed some key points about the language and the compiler.

Get the benefits of TypeScript now

A recent client project used TypeScript with React and Redux . Both React and Redux are familiar to me, and I also wrote modern JavaScript (ECMAScript 2016, ES6) for about 6 months.
One way to get started with TypeScript is to choose one of your favorite editors (eg Visual Studio Code , Sublime Text , or Atom ) and run the TypeScript compiler from there. I installed the TypeScript Sublime Plugin and tried some auto-completion suggestions on native HTML elements.

Tech Note: The text editor plugin leverages the Language Service, which is part of the TypeScript compiler's API. It is designed for text editing where low latency feedback is important to developers. It provides beautiful APIs such as getCompletionsAtPosition in the animation example above .

TypeScript and third party libraries

So far, I have not written TypeScript at all, just the ES5 source code file with the .ts extension. You can get more benefits from the compiler by getting the API description of the third party library. The API description is called Type Definition in TypeScript.
Let's download React, a famous View library, and its type definition. The type definition file can be identified from the file name "d", such as react.d.ts.
A tool that manages type definitions is called Typings .
To install Typings, npm install typings -grun.
You may find that Typing's command line API is familiar. It is very similar to the one used by npm.
After installing Typings, use the init command to generate a configuration file. Use the : typings init
search command with the –name flag to search for type definitions by name.
  1. > Typings Search - Name React
  2. Viewing 1 of 1
  3.  
  4. NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED
  5. react dt http : //facebook.github.io/react/ 2 2016-05-26T13:46:01.000Z
“Dt” represents the source location of the type definition. This can be, for example, npm or a well known site called Definitely Typed (dt). A list of sources can be found here .
Type definitions can be installed with the install command.
  1. Install Dt Typings React Dt React - Dom - Save
The –save flag behaves similarly to the npm –save flag. That is, typings initsave the type definition reference in the typing.json generated by.
I haven't installed React itself yet, but you can install it with npm.
  1. Install React React Npm - Dom - Save
What would be the development with a third party library and its type definition files? As an example, I created a React component with two properties and observed how auto completion works when using and editing it.
alt-text
In this example, we are adding an interface declaration as the first TypeScript snippet. I'm not strict in adding types everywhere, but it's helpful to describe the exposed entry points (such as component properties).

Advantages of type definition

Now you don't have to remember or peek at the API definition, and it's easier to use. Refactoring is also easier.
Now suppose you have a DemoComponent that is used in many other components and needs different properties . For example, suppose you have a name property that can be changed to other more specialized properties (username, surname, fullName, etc.). In short, if you do a search/replace with the keyword'.name' in a big project, you'll end up going. You have to check all the hits in your search for the right context. If the type is used in the right place, the name property will be more semantically sensitive, and will also let the tool know which name is affected by the refactoring.
alt-text
The example shown in the animation above is simple, but it's easy to imagine that you could do the same with a large codebase.

Misconceptions about types

When we hear "strong typing", we often think that "types are needed everywhere, like old (previous type interfaces) C# and Java code".
  1. IDictionary < int , Car > carsById = new Dictionary < int , Car >();
There is a lot of noise in this with no benefit.
TypeScript has a function called type inference, and if you enter the following, it will act to emit an error.
  1. let name = "tatu"
  2. name = 2 ; / // an error
It is inferred that name is a String , so it doesn't need to be explicitly stated.
TypeScript also has a feature called Contextual Type. Below is an example from the documentation .
  1. window . onmousedown = function ( mouseEvent ) {
  2. console . log ( mouseEvent . Buton ); // <- Error
  3. };
mouseEvent There is no type defined in, but still TypeScript is mouseEvent the button you can throw an error if it does not have a property called. Why is this possible?
That's because TypeScprit knows that the callback for onmousedown is a function that takes a MouseEvent type argument. The MouseEvent type has no button property. These checks can save developers time.

Use TypeScript with other tools

When I thought about the other tools I've used in JavaScript development, I've come up with the following: linting tools, Browserify/Webpack, testing frameworks, and BabelJS. Will TypeScript make these tools obsolete?

lint tool

If TypeScript is very powerful at catching errors, do you really need tools like ESLint or JSHint? The answer is yes. For example, in addition to checking for errors, ESLint can check code formats in terms of best practices and stylistics. Unfortunately ESLint compatibility relies on the TypeScript ESLint Parser project, which is still experimental.
The good news is that there is a tool called TSLint created for TypeScript .

Browserify/Webpack

Since TypeScript is not a bundle tool, for example, "I write my own code in TypeScript, but in the browser I am using lodash, which is a third-party library," TypeScript fetches lodash and fetches one file. Cannot be bundled with. It is Browserify/Webpack's role to bundle.

Test framework

I wrote a test in TypeScript, compiled it into JavaScript, and used Mocha to run the test and so on. I would like to hear your opinion on this.

BabelJS

Does TypeScript support ES2016 features, is BabelJS no longer needed? The answer is "it depends." We asked smart people about the benefits of BabelJS.

Author: "Can anyone please tell me why I have to use #babeljs instead of the #TypeScript compiler to transpile my ES2015 code?"
Tero Parviainen: "TypeScript currently uses async/await. I can't compile it to ES5. If I need these I have to use Babel etc. In

other words TypeScript supports async/await but I can't compile it into ECMAScript which all browsers understand ..
If you don't use this feature, you can remove BabelJS from the build process.
PS: Reader Birk Skyum pointed out that ES3 support for this feature is in the TypeScript roadmap and will be released in version 2.0.

When to use TypeScript

Most of the TypeScript blog posts mention that "TypeScript is intended for use in large projects." According to Anders Hejlsberg's JavaScript Jabber interview (30:50) ,
If you only write five lines of code, it wouldn't merit the effort of introducing TypeScript... The bigger the project, the more useful TypeScript becomes. As I said earlier, by the time it's thousands of lines of code, it's a slam dunk.
* I didn't know "Slam Dunk" and had to do a Google search. Apparently it's a basket term that refers to a simple shoot that is harder to remove.

Conclusion

Hopefully, at least, my TypeScript enthusiasm will be transmitted to you, and you will have another chance to TypeScript. I would love to hear if you succeeded in using TypeScript in a real project, or if you had a miserable experience. See you next time!
Discuss on Hacker News

0 コメント:

コメントを投稿