LoginSignup
12
7

More than 5 years have passed since last update.

Typescript基本文法メモ

Posted at

Typescriptに特徴的な部分のみ

連想配列

インデックスシグニチャでの型宣言
(シグネチャ=引数や返り値の組み合わせ)

let obj: { [key: string]: string; } = {
    "hoge": "ほげ",
    "huga": "ふが",
}
obj.piyo = "ぴよ";

型推論により、hogehuga以外のプロパティを受け入れなくなっている

let obj = {
    "hoge": "ほげ",
    "huga": "ふが",
}
obj.piyo = "ぴよ"; // エラー

共用型

複数の型を宣言する。どれかに該当すれば良い

let hoge: string | boolean;
hoge = "hoge";
hoge = true;
hoge = 1; // エラー

省略可な引数

引数の最後に?をつける。オプション。

function say(serif?: string) {
    console.log(serif);
}
say();

オーバーロード

// 最初に型チェックのためにシグニチャだけで関数を宣言する
function show(a: number): number;
function show(a: string, b: boolean): string;

// 上記に宣言したシグニチャの全てに対応する関数を実装する
function show(a: any, b: any): any {
  if (typeof a === "string") {
    return b ? "[true]" + a : "[false]" + a;
  }
  if(typeof a === "number"){
    return a;
  }
}

console.log(show("hoge", true)); // [true]hoge
console.log(show("hoge")); // [false]hoge
console.log(show(1)) // 1

コンストラクタとプロパティの生成・初期化の省略記法

コンストラクタの引数に必ずアクセス修飾子をつけること

class Person{
  constructor(private _name: string, private _age: number){}
  show() {
    console.log(`名前:${this._name} 年齢:${this._age}`);
  }
}

モジュール

内部モジュール = 名前空間
外部モジュール = ES2015のモジュール

構造的部分型

型の構造に着目。型を公称しなくても構造が一致すれば派生型とみなす。
(ある型のプロパティを持ってさえいればその型の派生とみなす)

interface Result{
    a: number;
    b: number;
}

function getTotal(result: Result): number {
    return result.a + result.b;
}

// a,bをnumberで持ってさえいれば、
// 他のプロパティcを持っていてもResult型とみなされる
var result = {
    a: 100,
    b: 50,
    c: "hello"
}

console.log(getTotal(result));

型としてのthis

this(自分自身)という型を返すことで、
メソッドチェーンが可能になる。

class MyClass{
  constructor(val: number){
    this._val = val;
  }
  get val(): number{
    return this._val;
  }
  add(val: number): this{
    this._val += val;
    return this;
  }
  minus(val: number): this{
    this._val -= val;
    return this;
  }
}

var myClass = new MyClass(10);
console.log(myClass.add(5).minus(3).val); // 12

参考
速習TypeScript: altJSのデファクトスタンダートを素早く学ぶ!
TypeScript入門 (全19回)

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