第15回 HTML5ビギナーズ #html5jbg
jQuery + TypeScript やってみた
@320kawashima 河島 美津雄 HTML5ビギナーズ 部長 html5j スタッフ 株式会社フリーセル所属
TypeScript http://www.typescriptlang.org/
お題 https://gist.github.com/funnythingz/9827773 ※シンプルにTypeScriptの部分だけやります
まずは準備 npm -g install typescript node.jsのパッケージをグローバルにインストール
TypeScriptの設定ファイル作 成 # 該当のディレクトまで移動 cd ディレクトリまでのパス # 設定ファイルの作成 tsc --init tsconfig.jsonが生成されます
TypeScript設定ファイルの内 容 { "compilerOptions": { "module": "amd", "target": "es5", "noImplicitAny": false, "outFile": "dist/js/common-typescript.js", "sourceMap": false }, "files": [ "src/ts/common-typescript.ts" ], "exclude": [ "node_modules" ] } https://www.typescriptlang.org/docs/handbook/compiler-options.html
jQueryの型定義ファイルを用 意 TypeScriptでjavascriptライブラリを読み込んで実行する場合 TypeScript型定義ファイル(.d.ts)が必要 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/jquery/jquery.d.ts typescriptファイル、ここではcommon-typescript.tsの最初に記述 /// <reference path="jquery.d.ts" />
コンパイル tsc
まずは完成物を確認 https://github.com/320kawashima/TypeScript_for_beginner
jQueryだけで作ったコードを確認
今回やってみたのは class interfaces(Class Types)
Class class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world"); Classとは、ある共通のものに対しての変数や関数を格納したもの。 Greeterというclassで、greetingというプロパティ、コンストラクタ、greetという メソッドを持っていて、インスタンスが生成された時点で中身を持ちます。引数は 型を明示すること。
Interface(Class Types) interface ClockInterface { currentTime: Date; } class Clock implements ClockInterface { currentTime: Date; constructor(h: number, m: number) { } } Intrefaceとは型を宣言した集合に名前がついたものです。 ClockInterfaceという名前のinterfaceで、Dateという型を持ったcurrentTimeがある ということが記載されています。
TypeScriptのコードを確認
2つのファイルを比較

jQuery+TypeScriptやってみた