More Related Content Similar to Buildinsider OFFLINE TypeScriptの基礎から実践・利用事例まで Similar to Buildinsider OFFLINE TypeScriptの基礎から実践・利用事例まで (20) More from Masahiro Wakame More from Masahiro Wakame (20) Buildinsider OFFLINE TypeScriptの基礎から実践・利用事例まで3. • Google App Engine
• Android
• Google Apps
などなど、
技術に特化した会社です。
3
5. • Windows!! ! → VMwareに…
• VisualStudio! → 持ってない
• ゴメンナサイッ ○┐
5
11. TypeScript the Great
• JSのSuperSet(上位セット)だよ!
• 全てのJSはTypeScriptである
• 可読性の高い変換後JSコード
• moduleある!classもある!継承もある!
• 型もあるよ!
• 既存の資産も捨てなくて済むよ!
• TypeScriptはロックインもされない!
11
23. var hoge = "hoge";
hoge.arimasen();
hoge = "fuga";
hoge = 1;
var fuga:any = "fuga";
fuga = 1;
変数について
• 型指定の省略も可能
• 右辺から自動的に推論される
• メソッドなどの存在チェックがされる
stringにarimasenメソッドはない
stringにnumberは入れられない
anyはなんでも!なるべく使わない
TS
23
24. クラスについて
• JSはプロトタイプベースのOOP
• 多くのプログラマに馴染みが薄い…
• TypeScriptはクラスベースなOOP!
class Test {
str:string;
constructor() {
this.str = "new";
}
showMessage():void {
alert(this.str);
}
}
new Test().showMessage();
var Test = (function () {
function Test() {
this.str = "new";
}
Test.prototype.showMessage = function () {
alert(this.str);
};
return Test;
})();
new Test().showMessage();
TS JS
http://goo.gl/G7t0U
24
25. class Test {
constructor(public str:string = "new"){
}
public showMessage():void {
alert(this.str);
}
}
var test = new Test();
test.str = "Hello";
test.showMessage();
クラスについて
• 省略記法が色々
• コンストラクタの引数をプロパティに
TS
http://goo.gl/7Hi7T
25
26. var func1 = function (str = "World") {
alert("Hello " + str);
}
var func2 = (str = "World") => {
alert("Hello " + str);
}
func1(); // Hello World
func2("にゃんこ"); // Hello にゃんこ
// func1(1);
関数について
• 書き方色々
• 通常のJSスタイル
• アロー関数式
TS
型が合わないのでエラー http://goo.gl/ArVFH
26
27. class Sample {
text = "Meow";
test() {
var func1 = function () {
alert(this.text);
};
var func2 = () => {
alert(this.text);
};
func1(); // undefined
func2(); // Meow
}
}
new Sample().test();
アロースタイルは便利
• 1つ外側の this が利用可能
• 不都合がない限りアロースタイルで
TS
Sample.prototype.test = function () {
var _this = this;
var func1 = function () {
alert(this.text);
};
var func2 = function () {
alert(_this.text);
};
func1();
func2();
};
JS
http://goo.gl/K6MU7
一部略
27
29. 引数について
• 省略可能引数
• デフォルト値付き引数
• 可変長引数
var func1 = (str?:string) => alert(str);
func1();
func1("Hello world");
var func2 = (str = "Hello world") => alert(str);
func2();
func2("Hello world");
var func3 = (...strs:string[]) => alert(strs.join(" "));
func3();
func3("Hello", "world");
http://goo.gl/Bt83S
29
30. module Sample {
export class Test {
static text = "Hello world";
}
class Internal {
}
}
alert(Sample.Test.text);
var Sample;
(function (Sample) {
var Test = (function () {
function Test() { }
Test.text = "Hello world";
return Test;
})();
Sample.Test = Test;
var Internal = (function () {
function Internal() { }
return Internal;
})();
})(Sample || (Sample = {}));
alert(Sample.Test.text);
モジュールについて
• C# のnamespace
• Java のpackage
• ネストも可能
TS
http://goo.gl/R7IK8
JS
30
31. interface Animal { walk(); }
interface Cat extends Animal { meow(); }
class NorwegianForestCat implements Cat {
walk() {
alert("四足とことこ");
}
meow() {
alert("にゃーん");
}
brushing() {
alert("毛が長いですごしごし");
}
}
var doWalk = (animal:Animal) => animal.walk();
doWalk(new NorwegianForestCat());
インターフェースについて
• C# や Java の interface と同じ
TS
http://goo.gl/RNH8J
31
32. 構造的部分型
• interface = 満たすべき仕様
• 仕様があってりゃえじゃないか
TSinterface MusicPlayer {
play(title:string);
}
var gameMusicPlayer =
(player:MusicPlayer) => {
player.play("Baba yetu");
}
// MusicPlayerを実装している
class Mp3Player implements MusicPlayer {
play(title:string) {
alert(title + "を再生します。");
}
}
gameMusicPlayer(new Mp3Player());
// MusicPlayerが要求するものを全て持っている
class 路上音楽家 {
play(title:string) {
alert(title + "がご希望ですか!");
}
}
gameMusicPlayer(new 路上音楽家());
// 実はクラスじゃなくても仕様を満たせばOK
gameMusicPlayer({
play: (title:string) => {
alert(title + "の再生")
}
});
http://goo.gl/JpjF3
32
34. public, private
• メソッドやプロパティをprivateに
• コンパイル時チェックのみ
• publicもprivateも生成されるJavaScriptに違い
class Sample {
private test1() {}
public test2() {}
}
var sample = new Sample();
sample.test1();
sample.test2();
var Sample = (function () {
function Sample() { }
Sample.prototype.test1 = function () {
};
Sample.prototype.test2 = function () {
};
return Sample;
})();
var sample = new Sample();
sample.test1();
sample.test2();
エラー
TS JS
http://goo.gl/5UTb2
34
35. class A {
constructor(public str:string, public num:number){}
}
class B {
constructor(private a:A, public bool:bool){}
get str() { return this.a.str; }
get num() { return this.a.num; }
}
var b = new B(new A("vvakame", 29), true);
alert(b.str + " " + b.num + " " + b.bool);
getter, setter
• get, set アクセサが定義できる
• サーバから貰った複数のデータを合成したり
するのに思いのほか便利
TS
http://goo.gl/V5pNv
35
36. cast
• <any> 最強です 稀に使います
• TypeScriptの利点が失われるので極力使用し
ちゃあダメ!
TSclass A {
}
class B {
}
var b1:B = new A();
var b2:B = <B> new A();
var b3:B = <any> new A();
両方エラー
http://goo.gl/12KMc
36
38. interface Message {
new (str:string):{
showMessage();
};
}
var func = (messageClass:Message) => {
new messageClass("Hello").showMessage();
};
class MessageImpl {
constructor(public str:string){}
showMessage() { alert(this.str); }
}
func(MessageImpl);
複雑な型
• new できる関数を表す型
• 以下のプロパティを持つ…
TS
http://goo.gl/0Tp8s
38
42. 既存資産の活用
interface IScope {
// Documentation says exp is optional, but actual implementaton counts on it
$apply(exp: string): any;
$apply(exp: (scope: IScope) => any): any;
$broadcast(name: string, ...args: any[]): IAngularEvent;
$destroy(): void;
$digest(): void;
$emit(name: string, ...args: any[]): IAngularEvent;
// Documentation says exp is optional, but actual implementaton counts on it
$eval(expression: string): any;
$eval(expression: (scope: IScope) => any): any;
// Documentation says exp is optional, but actual implementaton counts on it
$evalAsync(expression: string): void;
$evalAsync(expression: (scope: IScope) => any): void;
// Defaults to false by the implementation checking strategy
• AngularJS の場合
• angular.d.ts を利用 http://goo.gl/9NrZ4
42
43. 既存資産の活用
• 構造的部分型が大変良い!
• 整合性があっていればちゃんと使える
• JavaScriptの文化に馴染みやすい
interface Settings {
method:string;
url:string;
}
var doAjax = (settings:Settings) => { ... };
doAjax({
url: "http://topgate.co.jp/"
});
TS
不足があればコンパイルエラーになる
http://goo.gl/mv1To
43
45. サンプルコードを試す
• git clone git://github.com/vvakame/
typescript-project-sample.git
• 上記ディレクトリ直下で
• npm install
• bower install
• tsd install jquery
• grunt test
• grunt && node app.js
45
50. 必要なもののインストール
• npm install -g typescript
• npm install -g grunt-cli tsd bower
• phantomjs http://phantomjs.org/
npm は nodebrew や
chocolatey とかで入れる
50
53. TOPGATE社内利用例
• 現在1案件で利用中 (完了
• 工数3人月くらい (プログラマ2名
• AngularJS + TypeScript | GAE/J
• サーバ側UnitTestでクライアント側UnitTest用
のテストデータを生成
• CIサーバではPhantomsJSを活用
53
60. Generics
class ProcessedHttpPromiseImpl<T> {
constructor(
public promise:ng.IHttpPromise,
public preProcess:(data:any)=>T) {
}
success(callback:(data:T)=>void):ProcessedHttpPromise {
this.promise.success((original:any)=> {
var data:T = this.preProcess(original);
callback(data);
});
return this;
}
error(callback:HttpPromiseCallback):ProcessedHttpPromise {
this.promise.error(callback);
return this;
}
}
var promise: ProcessedHttpPromiseImpl<Sample> = ...;
promise.success((data) => {
// data は Sample としてしっかり型チェックされる
// Genericsがなかったらここは any で扱うしかない…!
data.test();
});
TS
60
61. • .d.ts 用
• 引数に応じて帰ってくるものの型が変わる
Specialized Signatures
interface Document {
createElement(tagName: string): HTMLElement;
createElement(tagName: "div"): HTMLDivElement;
createElement(tagName: "span"): HTMLSpanElement;
createElement(tagName: "canvas"): HTMLCanvasElement;
}
61
63. 参考
• G+ TypeScript
• http://goo.gl/RINqk
• わかめはてブ
• http://goo.gl/pUdoD
• TypeScript クイックガイド
• http://phyzkit.net/typescript/
63