TypeScript

Mapped Typesについて

Mapped Typesについて 既存の型を元に動的に新しい型を作る方法を提供する 構文 {[P in K]: T} P はこのMapped Typeの引数型 (parameter type) K はこのMapped Typeの制約型 (constraint type) T はこのMapped Typeのテンプレート型 (template type) 下記の…

keyofについて

keyofについて keyofにオブジェクトを指定すると、そのオブジェクトのいずれかのキー(プロパティ名)を許容するUnion Typeが返却される interface SampleInterface { a: string; b: number; c: boolean; } type Keys = keyof SampleInterface; const aKey: …

クラスについて

継承 abstract class Horse { private jockey: string; constructor(private jockey: string) { } run() { console.log(`${this.getName()}が${this.jockey}を乗せて走る`); } abstract getName(): string; } class MihonoBourbon extends Horse { construct…

Type Aliasについて

Type Alias 再利用したい型に対して名前をつけて管理するための仕組み type User = { id: number, name: string }; const u: User = { id: 1, name: "Jack" }; 交差型で拡張 交差型を使えばインタフェースの継承のようなことができる type GooType = { goo: …

interfaceについて

インタフェース interface SquareConfig { color?: string; width?: number; } function execute(config: SquareConfig): void { console.log(config); } // implementsする必要はなくて、型チェッカーはプロパティが一致してるかをチェックする execute({ c…

thisパラメータの補足

thisパラメータがイマイチよくわからなかったのでもうちょい調べた。。 thisパラメータ function f(this: void) { } 下記のような関数の場合、呼び出し元(コンテキスト)によってthisの参照が変わる為、正しく動作しない場合がある。 const obj = { name: "…

関数について

基本的な関数 // 名前付き関数 function add(x: number, y: number): number { return x + y; } // 無名関数 let myAdd = function(x: number, y: number): number { return x + y; }; 関数の型 type FuncType = (x: number, y: number) => number; const fu…

分割代入について

分割代入 配列やオブジェクトの中身を別の変数へ分割して代入する仕組み 配列の分割代入 const input = [1, 2]; const [first, second] = input; console.log(first); // 1を出力 console.log(second); // 2を出力 let [first, ...rest] = [1, 2, 3, 4]; con…

交差型(Intersection Types)と共用体型(Union Types)について

交差型(Intersection Types)と共用体型(Union Types)について 交差型(Intersection Types) T & U TとUの両方を満たす型を動的に生成できる type T = { foo: string }; type U = { bar: number }; type I = T & U; // fooまたはbarのいずれかが未定義の場合は…