LoginSignup
9
10

More than 5 years have passed since last update.

Typescriptでコンパイルすればいい!!誰が書いてもある程度Javascriptの質が担保できる!?

Last updated at Posted at 2013-07-03

TypeScript は新しい言語ではなく、JavaScript のスーパーセットで、強力でかつ型指定が可能です。そのため、すべての JavaScript は TypeScript として有効であり、コンパイラが生成するのは JavaScript です。

【公式】Typescriptを参考

導入

事前準備

node.jsは導入済み
npmは導入済みである事

インストール

$ npm install -g typescript

サンプル作成

まず最初にサンプルのtypescriptを作成します。

$ vim sample.ts

class shop {
  price: number;
  num: number;
  constructor() {
    this.num = 10;
  }
  setPrice(price: number) {
    this.price = price;
  }
  calculatePrice() {
    var total: number = this.num * this.price;
    return this.price + '円のりんごを' + this.num + '個購入した場合' + total + '円です。';
  }
}
var sp = new shop();
sp.setPrice(1000);
document.body.innerHTML = sp.calculatePrice();

コンパイルの実行

$ tsc sample.ts

lsでコンパイル結果を見る

$ ls sample.*
sample.js    sample.ts

コンパイルで生成したjavascriptを見る

$ vim sample.js 

var shop = (function () {
    function shop() {
        this.num = 10;
    }
    shop.prototype.setPrice = function (price) {
        this.price = price;
    };
    shop.prototype.calculatePrice = function () {
        var total = this.num * this.price;
        return this.price + '円のりんごを' + this.num + '個購入した場合' + total + '円です。';
    };
    return shop;
})();
var sp = new shop();
sp.setPrice(1000);
document.body.innerHTML = sp.calculatePrice();

このコードをブラウザで表示すると
「1000円のりんごを、10個購入した場合、10000円です。」と表示されます。
ちゃんと計算されてます。
では、次に型宣言を無視して、計算出来ないようにしてみたらどうなるのか、確認します。

$ vim sample.ts

class shop {
  price: number;
  num: number;
  constructor() {
    this.num = 10;
  }
  setPrice(price: number) {
    this.price = price;
  }
  calculatePrice() {
    var total: number = this.num * this.price;
    return this.price + '円のりんごを' + this.num + '個購入した場合' + total + '円です。';
  }
}
var sp = new shop();
sp.setPrice('1000');
document.body.innerHTML = sp.calculatePrice();


$ tsc sample.ts 
sample.ts(20,4): error TS2081: Supplied parameters do not match any signature of call target.
sample.ts(20,4): error TS2087: Could not select overload for 'call' expression.

もし、このコードが正常にコンパイルされていたとしたら、
this.num(number) * this.price(string)の計算処理が行われるjavascriptが作成されていましたが、ちゃんとエラーが出ました。
この様に、型を宣言する事で、想定外の値が導入された場合、エラーが発生してしまう場所を
未然に防ぐ事ができます。

ま、この例ではjavascriptは作成されちゃうのですが、、、、
今回は、型エラーがちゃんと出るという事を確認出来たので、OKです。

※前はデザイナにも知ってほしいと書いていたのですが
内容的に、エンジニアよりに書きすぎていたため、タイトルを変更しました。
時間を見つけて、デザイナに何故知ってほしいのかを、別に書いてみたいと思います。

9
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10