TypeScriptのチートシート。
公式の チートシート(画像 PNGとPDF) もある。ドキュメントは ここ
目次
 
型
プリミティブ型
- string: 文字列
- number: 数値 整数と小数
- boolean: 真偽値 true/false
- null: null値
- undefined: 未定義
- any: 任意の型。型チェックを無効にする。
- void: 関数が何も返さないことを示す。
- unknown: 型が不明な場合。anyとは異なり型を確定させないとメソッドは使えない。
- symbol: 一意で変更不可能な値。
- bigint: 大きい整数。 BigInt literals are not available when targeting lower than ES2020(ES2020 以前では使用不可)
- never: 到達しない値を表す型。never型の変数は存在しないし、関数は正常に終わらないことを示す。
型アサーション
any とか unknown だったり HTML 要素の型を明確にする
const a: any = "Hello World";
// as を使って型を断定
const b = (a as string).toUpperCase();
// ジェネリクスと同じような書き方 (as を使ったほうがいい)
const c = <string>a.toUpperCase();
// オブジェクトに追加する
const d: unknown = {
  foo: 100,
  bar: 200,
};
(d as any)["baz"] = 300;
// OR
(d as { [key: string]: number })["baz"] = 300;
// OR
(<{ [key: string]: number }>d)["baz"] = 300;
// 以下はコンパイルは通るかもしれないけどリンターはエラー
d["baz"] = 300;型チェック
型判定で TypeScript 特有の何かがあるわけではない。
console.log(typeof "" == "string"); // true
console.log(typeof 0 == "number"); // true
console.log(typeof undefined == "undefined"); // true
console.log(typeof function () {} == "function"); // true
// null
console.log(typeof null); // "object"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
// 配列
console.log(typeof []); // "object"
console.log(Array.isArray([])); // true
// オブジェクト
console.log(typeof {}); // "object"
console.log(Object.prototype.toString.call({})); // "[object Object]"
// インスタンス
const re = new RegExp("pattern");
console.log(re instanceof RegExp); // true
 
変数/定数/分割代入
// 変数
let a: string, b: number;
a = "Hello World";
b = 100;
// 一行。値を見て型がわかる場合はわざわざ型を書く必要はない
let c: string = "Hello World";
// ユニオン型。複数の型を | 区切りで指定する
let d: string | undefined;
d = "Hello World";
// 定数
const e: string = "Hello World";
const f: number = 100;
const g: number = 3.14; // 小数も number
const h: boolean = true;
// 分割代入(配列)
const [i, j, ...k]: [string, boolean, ...number[]] = ["Hello", true, 10, 20];
// Hello true [ 10, 20 ]
// 分割代入(オブジェクト)
const { foo, bar, baz }: { foo: string; bar: number; baz: boolean } = {
  foo: "hello",
  bar: 100,
  baz: true,
};Null 合体演算子 (??)
初期値を設定するのに便利(JavaScript でも同じ)
const nullValue = null;
const undefValue = undefined;
const emptyValue = "";
const zeroValue = 0;
// ?? は undefined か null であれば ?? の右側の値が使われる。
const a = nullValue ?? "Default Value";
console.log(a); // Default Value
const b = undefValue ?? "Default Value";
console.log(b); // Default Value
const c = emptyValue ?? "Default Value";
console.log(c); // ""
const d = zeroValue ?? "Default Value";
console.log(d); // 0
// || は false と評価される場合に || の右側の値が使われる。
const e = nullValue || "Default Value";
console.log(e); // Default Value
const f = undefValue || "Default Value";
console.log(f); // Default Value
const g = emptyValue || "Default Value";
console.log(g); // Default Value
const h = zeroValue || "Default Value";
console.log(h); // Default Value
// ?? を使えば参考演算子を使わなくて済む
const i = typeof undefValue == "undefined" ? "Default Value" : undefValue;
 
配列
初期化
const a: string[] = []; // []
const b: string[] = new Array(5); // [ <5 empty items> ]
const c = <string[]>new Array(5);
const d = new Array(5) as string[];
// 確保した長さを初期値で埋める
const e: number[] = new Array(5).fill(0); // [ 0, 0, 0, 0, 0 ]
const f: string[] = new Array(5).fill(""); // [ '', '', '', '', '' ]変更不可
const a: readonly number[] = [10, 20, 30];
a[0] = 100; // Index signature in type 'readonly number[]' only permits reading.連結
// 連結
const f: number[] = [10, 20, 30];
const g: number[] = [...f, 40, 50, 60];
 
オブジェクト
let o: {
  name: string;
  readonly id: number; // 変更不可
  message?: string; // オプショナル。 string | undefined と同じ
  profile: () => void; // 関数
  profile(): void; // 関数
};追加可能なオブジェクト
const o: {
  [key: string]: number;
} = {};
o["prop"] = 100;変更不可なオブジェクト
as const で Object.freeze
の様に変更不可にできる。
const o = {
  name: "Michael",
  id: 1,
  profile() {
    console.log(this.name, this.id);
  },
} as const;
o.name = "James"; // エラープロパティの確認
const o = {
  prop: "Hello World",
};
const hasProp = o.hasOwnProperty("prop");
console.log(hasProp); // true
const isThere = "prop" in o;
console.log(isThere); // trueオプショナルチェイニング演算子(Optional Chaining)
const o: {
  [key: string]: string;
} = {
  text: "Hello World",
};
const a = o.text?.toLocaleUpperCase();
console.log(a); // HELLO WORLD
// プロパティが存在しなくてもエラーにならない。存在しなければ undefined が返る
const b = o.unknown?.toLocaleUpperCase();
console.log(b); // undefined
// プロパティ名が存在しない場合はエラーになるビックリマークもある。エラーを投げる手間が省ける
const c = o.unknown!.toLocaleUpperCase();
console.log(c);
 
関数
省略可能な引数
function fn(name: string, value?: string) {
  ...
}可変長引数
function fn(name: string, ...args: string[]) {
  ...
}初期値
function fn(name: string = "anonymous"): void {
  ...
}値の選択肢
function fn(size: "small" | "medium" | "large"): void {
  ...
}複数の戻り値
// 配列を返す
const [a, b] = ((): [string, number] => { return ["hello", 100]; })();
// オブジェクトを返す
const { c, d } = ((): { c: string; d: number } => { return { c: "hello", d: 100 }; })();関数を返す
function fn(): (name: string) => void {
  return (name: string): void => {};
  // OR
  return (name: string) => void {};
}
 
type 型の定義
オブジェクト
// オブジェクト
type A = {
  // オプショナル。無くてもよい
  name?: string;
  // 変更不可
  readonly id: number;
  // 関数。書き方は以下の二通り
  method(): void;
  method: () => void;
};
// 定義
const a: A = {
  id: 100,
  method() {
    console.log("Hello World");
  },
};関数
type Callback = (a: string, b: number) => boolean;ユニオン型
type A = "small" | "medium" | "large";
type B = string | number | boolean;
class C {}
class D {}
class E {}
type F = C | D | E;
 
interface インターフェース
interface A {}
interface B {}
interface C extends A, B {
  // オプショナル。実装しなくてもよい
  name?: string;
  // 変更不可
  readonly id: number;
  // 関数。書き方は以下の二通り
  method(): void;
  method: () => void;
}
// 実装
class D implements C {
  name = "James";
  readonly id: number;
  constructor() {
    this.id = 100;
  }
  method() {
    console.log("Hello World");
  }
}
 
class クラス
class A extends B implements C, D {
  // オプショナル。値を代入しない場合は undefined
  name?: string;
  // パブリック
  public publicValue: string = "public";
  // プライベート
  #privateValue: string = "private"; // javascriptのクラスと同じ
  private privateValue: string = "private";
  // 静的変数
  static staticValue: string = "static";
  // 初期化移行変更不可
  readonly id: number;
  // セッター/ゲッター
  #age: number = 0;
  set age(n: number) {
    this.#age = n;
  }
  get age(): number {
    return this.#age;
  }
  // private,public を引数に付けるとそのままインスタンス変数になる。定義や代入の手間が省ける
  constructor(private message: string) {
    super();
    this.id = 100;
    console.log(this.message); // Hello World
  }
}
new A("Hello World");シングルトン
class A {
  private static instance?: A;
  // コンストラクターをプライベートにできる
  private constructor() {}
  public static new(): A {
    // this で instance にアクセスできる
    if (typeof this.instance == "undefined") {
      this.instance = new A();
    }
    return this.instance;
  }
}
A.new();
 
ジェネリクス
関数
function fn<T>(value: T): T {
  return value;
}
// OR
const fn = <T>(value: T): T => {
  return value;
};
const a = fn<string>("Hello World");
console.log(a); // Hello World
const b = fn<number>(100);
console.log(b); // 100
// 引数の型
fn<string>("Hello World");
// 戻り値の型
<string>fn("Hello World");
// 両方
<string>fn<string>("Hello World");class クラス
class A<T> {
  constructor(private values: T[]) {}
  public *generate() {
    for (const v of this.values) {
      yield v;
      console.log("--");
    }
  }
}
const a = new A<number>([10, 20, 30]);
for (const v of a.generate()) {
  console.log(v);
  // 10
  // --
  // 20
  // --
  // 30
  // --
}
 

コメント
コメントを投稿