LoginSignup
2
1

More than 3 years have passed since last update.

TypeScript メモ

Posted at

基本的なデータ型と宣言方法

var a: string = ''
var b: number = 10
var c: boolean = false
var d1: string[] = ['hello', 'world', 'something']
var d2: number[] = [1, 3, 4]
var e: any //どんなデータ型でも格納可能

関数の書き方

//返り値がある場合
function add(a: number, b: number): number{
  return a + b
}

//返り値がない場合
function add(a: number, b: number): void{
  //処理内容記載...
}

通常の関数宣言だけでなく、式のように関数を書くことができる。

// 通常の関数式
var addNormal = function(a: number, b: number): number{
  return a + b
}

// アロー記法
var addArrow = (a:number, b:number): number => {
  return a + b
}

// ワンライナー記法
var addArrowOneLiner = (a: number, b: number): number => a + b

console.log(addNormal(6, 10))$
console.log(addArrow(60, 100))$
console.log(addArrowOneLiner(600, 1000))$

関数のオーバーロード

function add(a: number, b: number): number //引数と返り値の組み合わせをシグナチャと呼ぶ
function add(a: string, b: string): string

function add(a: any, b: any): any{
  if (typeof a === "string" && typeof b === "string"){
    return a + ' ' + b
  }
  return a + b
}

クラス

クラス定義
コンストラクタ
インスタンス化
動作確認

class User {
  constructor(public name: string){
    this.name = name
  }

  sayHello(): void{
    console.log('hello ' + this.name)
  }
}

Getter/Setter
Userのプロパティに対するアクセスを制限するためにprivate修飾子をつける。

class User {
  constructor(private _name: string){ //privateの変数には慣習的に「_」をつける
  }

  public sayHi(): void{
    console.log('hi! i am ' + this._name)
  }

  get name() {
    return this._name
  }

  set name(newValue: string){
    this._name = newValue
  }
}
2
1
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
1