2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

typescriptの導入 + classについてのメモ

Posted at

###TypeScriptのインストール

npm install typescript

###typescriptの実行
.tsファイルを.jsファイルにコンパイルし、作成された.jsファイルを実行する。

tsc ファイル名.ts
node ファイル名.js

###typescriptでclassの練習

practice.ts

//クラスを作成
class Animal {

    //プロパティ  名前:型
    name: string;
    age: number;  //intではない

    //コンストラクタはインスタンスに引数を持たせる場合に必要    
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

}

//インスタンスを作成
var cat = new Animal("Cat", 7);
console.log(cat.name); //Cat
console.log(cat.age); //7


//コンストラクタは省略が可能
class Animal_no_constructor {

    name: string = "Dog";
    age: number = 3;

}

//コンストラクタを省略した場合は、インスタンスに値を持たせることが出来ない
var dog = new Animal_no_constructor();
//プロパティを出力
console.log(dog.name); //Dog
console.log(dog.age); //3


//メソッドの使い方
class Human {

    name: string;
    score: number;

    constructor(name: string, score: number) {
        this.name = name;
        this.score = score;
    }

    judge() {

        var message: string;

        if (this.score > 50) {
            message = this.name + "は合格";
        } else {
            message = this.name + "は不合格";
        }

        console.log(message);

    }

}

var takeshi = new Human("Takeshi", 100);
takeshi.judge(); //Takeshiは合格

var taro = new Human("Taro", 45);
taro.judge(); //Taroは不合格


//継承
class Oya {

    name: string;

    constructor(name: string) {
        this.name = name;
    }

    hello() {
        console.log("こんちわー");
    }

}

class Kodomo extends Oya {

    constructor(name: string) {
        //Oyaのthis.nameを受け継ぐ
        super(name);
        this.name = name;
    }
    
    say() {
        //親クラスOyaのhelloメソッド
        super.hello();
        console.log("あの" + this.name + "!?");
    }

}

var yoshida = new Kodomo("yoshida");
yoshida.say(); //こんちわー あのyoshida!?


//デフォルト引数
class Menu {

    item_number: number;

    constructor(item_number: number = 0) {
        this.item_number = item_number;
    }

    say_item_name() {
        var array = ["ラーメン", "うどん", "蕎麦"];
        console.log(array[this.item_number]);
    }

}

var soba = new Menu(2);
soba.say_item_name(); //蕎麦

var wasureta = new Menu();
wasureta.say_item_name(); //ラーメン(引数がないので自動で0に)

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?