ユーティリティ型

TypeScriptは、一般的な型の変換を容易にするために、いくつかのユーティリティ型を提供します。これらのユーティリティはグローバルに利用できます。

Awaited<Type>

リリース: 4.5

この型は、async関数でのawaitや、Promise.then()メソッドのように、Promiseを再帰的にアンラップする方法をモデル化することを目的としています。

ts
type A = Awaited<Promise<string>>;
type A = string
 
type B = Awaited<Promise<Promise<number>>>;
type B = number
 
type C = Awaited<boolean | Promise<number>>;
type C = number | boolean
Try

Partial<Type>

リリース済み
2.1

Typeのすべてのプロパティをオプションに設定した型を構築します。このユーティリティは、指定された型のすべてのサブセットを表す型を返します。

ts
interface Todo {
title: string;
description: string;
}
 
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
 
const todo1 = {
title: "organize desk",
description: "clear clutter",
};
 
const todo2 = updateTodo(todo1, {
description: "throw out trash",
});
Try

Required<Type>

リリース済み
2.8

Typeのすべてのプロパティを必須に設定した型を構築します。 Partialの反対です。

ts
interface Props {
a?: number;
b?: string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 };
Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.2741Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
Try

Readonly<Type>

リリース済み
2.1

Typeのすべてのプロパティをreadonlyに設定した型を構築します。つまり、構築された型のプロパティは再割り当てできません。

ts
interface Todo {
title: string;
}
 
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
 
todo.title = "Hello";
Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.
Try

このユーティリティは、実行時に失敗する代入式(例えば、凍結されたオブジェクトのプロパティを再代入しようとする場合など)を表現するのに役立ちます。

Object.freeze
ts
function freeze<Type>(obj: Type): Readonly<Type>;

Record<Keys, Type>

リリース済み
2.1

プロパティキーがKeysで、プロパティ値がTypeであるオブジェクト型を構築します。このユーティリティは、ある型のプロパティを別の型にマッピングするために使用できます。

ts
interface CatInfo {
age: number;
breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
 
cats.boris;
const cats: Record<CatName, CatInfo>
Try

Pick<Type, Keys>

リリース済み
2.1

Typeからプロパティの集合Keys(文字列リテラルまたは文字列リテラルのユニオン)を選択して型を構築します。

ts
interface Todo {
title: string;
description: string;
completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
 
todo;
const todo: TodoPreview
Try

Omit<Type, Keys>

リリース済み
3.5

Typeからすべてのプロパティを選択し、次にKeys(文字列リテラルまたは文字列リテラルのユニオン)を削除して型を構築します。Pickの反対です。

ts
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
 
todo;
const todo: TodoPreview
 
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
 
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
 
todoInfo;
const todoInfo: TodoInfo
Try

Exclude<UnionType, ExcludedMembers>

リリース済み
2.8

UnionTypeから、ExcludedMembersに代入可能なすべてのユニオンメンバーを除外して型を構築します。

ts
type T0 = Exclude<"a" | "b" | "c", "a">;
type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
type T2 = string | number
 
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
 
type T3 = Exclude<Shape, { kind: "circle" }>
type T3 = { kind: "square"; x: number; } | { kind: "triangle"; x: number; y: number; }
Try

Extract<Type, Union>

リリース済み
2.8

Typeから、Unionに代入可能なすべてのユニオンメンバーを抽出して型を構築します。

ts
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;
type T1 = () => void
 
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
 
type T2 = Extract<Shape, { kind: "circle" }>
type T2 = { kind: "circle"; radius: number; }
Try

NonNullable<Type>

リリース済み
2.8

Typeからnullundefinedを除外して型を構築します。

ts
type T0 = NonNullable<string | number | undefined>;
type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
type T1 = string[]
Try

Parameters<Type>

リリース済み
3.1

関数型Typeのパラメータで使用される型からタプル型を構築します。

オーバーロードされた関数の場合、これは*最後の*シグネチャのパラメータになります。 条件型内での推論を参照してください。

ts
declare function f1(arg: { a: number; b: string }): void;
 
type T0 = Parameters<() => string>;
type T0 = []
type T1 = Parameters<(s: string) => void>;
type T1 = [s: string]
type T2 = Parameters<<T>(arg: T) => T>;
type T2 = [arg: unknown]
type T3 = Parameters<typeof f1>;
type T3 = [arg: { a: number; b: string; }]
type T4 = Parameters<any>;
type T4 = unknown[]
type T5 = Parameters<never>;
type T5 = never
type T6 = Parameters<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T6 = never
type T7 = Parameters<Function>;
Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.
type T7 = never
Try

ConstructorParameters<Type>

リリース済み
3.1

コンストラクタ関数型の型からタプル型または配列型を構築します。すべてのパラメータ型(またはTypeが関数でない場合は型never)を持つタプル型を生成します。

ts
type T0 = ConstructorParameters<ErrorConstructor>;
type T0 = [message?: string]
type T1 = ConstructorParameters<FunctionConstructor>;
type T1 = string[]
type T2 = ConstructorParameters<RegExpConstructor>;
type T2 = [pattern: string | RegExp, flags?: string]
class C {
constructor(a: number, b: string) {}
}
type T3 = ConstructorParameters<typeof C>;
type T3 = [a: number, b: string]
type T4 = ConstructorParameters<any>;
type T4 = unknown[]
 
type T5 = ConstructorParameters<Function>;
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.
type T5 = never
Try

ReturnType<Type>

リリース済み
2.8

関数Typeの戻り値の型で構成される型を構築します。

オーバーロードされた関数の場合、これは最後のシグネチャの戻り値の型になります。「条件型内での推論」を参照してください。

ts
declare function f1(): { a: number; b: string };
 
type T0 = ReturnType<() => string>;
type T0 = string
type T1 = ReturnType<(s: string) => void>;
type T1 = void
type T2 = ReturnType<<T>() => T>;
type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T3 = number[]
type T4 = ReturnType<typeof f1>;
type T4 = { a: number; b: string; }
type T5 = ReturnType<any>;
type T5 = any
type T6 = ReturnType<never>;
type T6 = never
type T7 = ReturnType<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any
type T8 = ReturnType<Function>;
Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.
type T8 = any
Try

InstanceType<Type>

リリース済み
2.8

Type内のコンストラクター関数のインスタンス型で構成される型を構築します。

ts
class C {
x = 0;
y = 0;
}
 
type T0 = InstanceType<typeof C>;
type T0 = C
type T1 = InstanceType<any>;
type T1 = any
type T2 = InstanceType<never>;
type T2 = never
type T3 = InstanceType<string>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any
type T4 = InstanceType<Function>;
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.
type T4 = any
Try

ThisParameterType<Type>

リリース済み
3.3

関数型のthisパラメーターの型を抽出します。関数型にthisパラメーターがない場合は、unknownになります。

ts
function toHex(this: Number) {
return this.toString(16);
}
 
function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}
Try

OmitThisParameter<Type>

リリース済み
3.3

Typeからthisパラメーターを削除します。Typeに明示的に宣言されたthisパラメーターがない場合、結果は単純にTypeになります。それ以外の場合は、thisパラメーターのない新しい関数型がTypeから作成されます。ジェネリックは消去され、最後のオーバーロードシグネチャのみが新しい関数型に伝播されます。

ts
function toHex(this: Number) {
return this.toString(16);
}
 
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
 
console.log(fiveToHex());
Try

ThisType<Type>

リリース済み
2.3

このユーティリティは、変換された型を返しません。代わりに、コンテキスト上のthis型のマーカーとして機能します。このユーティリティを使用するには、noImplicitThisフラグを有効にする必要があることに注意してください。

ts
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
};
 
function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
let data: object = desc.data || {};
let methods: object = desc.methods || {};
return { ...data, ...methods } as D & M;
}
 
let obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx; // Strongly typed this
this.y += dy; // Strongly typed this
},
},
});
 
obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);
Try

上記の例では、makeObjectへの引数内のmethodsオブジェクトには、ThisType<D & M>を含むコンテキスト型があるため、methodsオブジェクト内のメソッド内のthisの型は{ x: number, y: number } & { moveBy(dx: number, dy: number): void }になります。methodsプロパティの型が、同時にメソッド内のthis型の推論ターゲットおよびソースになることに注意してください。

ThisType<T>マーカーインターフェースは、lib.d.tsで宣言された単なる空のインターフェースです。オブジェクトリテラルのコンテキスト型で認識されるだけでなく、このインターフェースは他の空のインターフェースと同様に機能します。

組み込み文字列操作型

Uppercase<StringType>

Lowercase<StringType>

Capitalize<StringType>

Uncapitalize<StringType>

テンプレート文字列リテラルに関する文字列操作を支援するために、TypeScriptには型システム内の文字列操作に使用できる一連の型が含まれています。これらは、テンプレートリテラル型のドキュメントで確認できます。

TypeScriptのドキュメントはオープンソースプロジェクトです。これらのページの改善にご協力ください。プルリクエストを送信して

このページの貢献者
Cchristian (54)
OTOrta Therox (23)
Bbob1983 (4)
JBJack Bates (3)
JJetLu (2)
32+

最終更新日: 2024年3月21日