TypeScript基礎文法メモ

```typescript

//文字列型
var title: string = 'Angular';
title = 'Aungular!';

//数値型
var n: number = 9;

//真偽値型
var isOpen: boolean = true;

//配列型
var keywords: (string | number)[] = ['name', 'email', 'body', 0];

//タプル型
var payment: [number, string, number] = [1, 'apple', 3000];

//オブジェクト型
var object: { [key: string]: string } = {
  id: 'test',
};

var post: object = [{ id: 12, content: 'lorem ipsum' }];

//共用型(Union型)
var sample: string | number;
sample = 'Yuya';
sample = 100;
//sample = true;  error

//enum型
enum KeyCode {
  Backspace = 8,
  Tab = 9,
  Enter = 13,
}
console.log(KeyCode.Backspace); //8

enum ErrorCode {
  OK = 200,
  BAD_RESPONSE = 400,
  UNAUTHORIZED = 401,
}

console.log(ErrorCode.OK); //200

//値を入れない場合はインデックスが表示される
enum Character {
  Bob, //0
  Dad, //1
  Tom, //2
}

console.log(Character.Bob); //0

//any型
var something: any = 'foo';
something = 100;
something = true;
something = { id: 1 };

//null,undefined型
var el: Element | null = document.querySelector('#app');
var foo: undefined = undefined;

//型を指定しない場合:自動で型解釈される
var unknown = 'string'; //string型と解釈される
//unknown = 100; //error

//let
//let fooo = 'foo';
let date = new Date();

//ブロック内でしか使えない変数
if (true) {
  let fooo = 'foo';
}
//console.log(fooo);  //参照出来ない

for (var i = 0; i < 5; i++) {
  console.log(i); // 0~4
}
console.log(i); //5

for (let j = 0; j < 5; j++) {
  console.log(j); //0~4
}
//console.log(j);  // 参照出来ない

var hoge = 'hoge';

function logHoge() {
  //var hoge;    //暗黙的に定義される
  //console.log(hoge); //undefined
  let hoge = 'new hoge!'; //letを使うと変数の巻き上げが起こらない
  console.log(hoge); //new hoge!
}

logHoge();

//定数
const currentYear: number = 2023;
//currentYear = 2021;  //error

//テンプレート文字列(Template Literals)
let templete1 = `This is Teplate strings.`; //バッククォートで囲む
let nam = 'Yuya Kubo';
let template2 = `
  Hello, TypeScript tutorial.
  Thank you. ${nam}
`;

console.log(template2); //改行はそのまま出力される

//スプレッド演算子
let categories = ['post', 'news', 'info'];
//...categories

//複製
let copyCat = [...categories]; //新しく配列が生成されている
console.log(copyCat); //["post", "news", "info"]
//連結
let pushCat = ['other', ...categories];
console.log(pushCat); //["other", "post", "news", "info"]

let unshiftCat = [...categories, 'other'];
console.log(unshiftCat); //["post", "news", "info", "other"]

//途中に挿入
let insertCat = ['other', ...categories, 'Q&A'];
console.log(insertCat); //["other","post", "news", "info", "post","Q&A"]

//2つの配列をマージ
let mergeCat = [...categories, ...copyCat];
console.log(mergeCat); //["post","news","info","post","news","info"]

//オブジェクト
let post2 = { id: 1, content: 'dummy', created: '2020-04-01' };

let copyObj = { ...post2 };
console.log(copyObj); //{id: 1, content: "dummy", created: "2020-04-01"}

let pushObj = { ...post, updated: '2020-04-05' };
console.log(pushObj); //{0: {…}, updated: "2020-04-05"}

let mergeObj = { ...post2, ...pushObj };
console.log(mergeObj); //{0: {…}, id: 1, content: "dummy", created: "2020-04-01", …}

//分割代入
let categories2 = ['post', 'news', 'info', 'other'];

//let a = categories2[0];
//let b = categories2[1];
let [a, b] = categories2;
console.log(a, b); // post news

let pos = { id: 1, content: 'dummy', created: '2020-04-01' };

const { id, content: body } = pos; //contentをbodyに変更
console.log(id, body); //取り出した階層が深いときに役立つ  1 dummy

//関数
function greet(name: string = 'Yuya'): void {
  //返り値も指定している voidは書かないことが多い
  console.log(`Helllo,world! ${name}`);
}

greet('Kubo'); //Helllo,world! Kubo
greet(); //?を引数につけると引数の省略が可能   初期値を設定している場合も同様   Helllo,world! Yuya

//可変長引数 スプレッド演算子で配列にできちゃう
function sum(...values: number[]): number {
  return values.reduce(function (prev, current) {
    //ちょっとここむずい
    return prev + current;
  });
}
console.log(sum(1, 3, 5, 9)); //引数の数は不定   18

//アロー関数
//() => {}

let add = (x1: number, x2: number): number => {
  return x1 + x2;
};
console.log(add(1, 3)); //4

//クラス　
class Animal {
  age: number = 10;
  private _legs = 3;

  constructor(public isCry: boolean) {
    //this.isCry = isCry;  //アクセス修飾子つけたら必要なくなる
  }

  cry(): void {
    if (this.isCry) {
      alert(`age: ${this.age}`);
    }
  }
  //アクセサメソッド(getter,setter)
  get legs() {
    return this._legs;
  }

  set legs(value: number) {
    this._legs = value;
  }
}

let dog = new Animal(true);
//dog.cry();//age: 10
dog.isCry = false;
dog.cry();  //何も起きない
dog.legs = 4;
console.log(dog.legs); //4

//継承
class Dog extends Animal {
  cry(): void {
    console.log('dog is cry');
    super.cry();
  }
}

let dog2 = new Dog(true);
dog2.cry(); // dog is cry , age: 10

```