TypeScriptは、一般的な型の変換を容易にするために、いくつかのユーティリティ型を提供します。これらのユーティリティはグローバルに利用できます。
Awaited<Type>
リリース: 4.5
この型は、async
関数でのawait
や、Promise
の.then()
メソッドのように、Promise
を再帰的にアンラップする方法をモデル化することを目的としています。
例
tsTry
typeA =Awaited <Promise <string>>;typeB =Awaited <Promise <Promise <number>>>;typeC =Awaited <boolean |Promise <number>>;
Partial<Type>
リリース済み
2.1
Type
のすべてのプロパティをオプションに設定した型を構築します。このユーティリティは、指定された型のすべてのサブセットを表す型を返します。
例
tsTry
interfaceTodo {title : string;description : string;}functionupdateTodo (todo :Todo ,fieldsToUpdate :Partial <Todo >) {return { ...todo , ...fieldsToUpdate };}consttodo1 = {title : "organize desk",description : "clear clutter",};consttodo2 =updateTodo (todo1 , {description : "throw out trash",});
Required<Type>
リリース済み
2.8
Type
のすべてのプロパティを必須に設定した型を構築します。 Partial
の反対です。
例
tsTry
interfaceProps {a ?: number;b ?: string;}constobj :Props = {a : 5 };constProperty '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>'.: obj2 Required <Props > = {a : 5 };
Readonly<Type>
リリース済み
2.1
Type
のすべてのプロパティをreadonly
に設定した型を構築します。つまり、構築された型のプロパティは再割り当てできません。
例
tsTry
interfaceTodo {title : string;}consttodo :Readonly <Todo > = {title : "Delete inactive users",};Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.todo .= "Hello"; title
このユーティリティは、実行時に失敗する代入式(例えば、凍結されたオブジェクトのプロパティを再代入しようとする場合など)を表現するのに役立ちます。
Object.freeze
ts
function freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys, Type>
リリース済み
2.1
プロパティキーがKeys
で、プロパティ値がType
であるオブジェクト型を構築します。このユーティリティは、ある型のプロパティを別の型にマッピングするために使用できます。
例
tsTry
interfaceCatInfo {age : number;breed : string;}typeCatName = "miffy" | "boris" | "mordred";constcats :Record <CatName ,CatInfo > = {miffy : {age : 10,breed : "Persian" },boris : {age : 5,breed : "Maine Coon" },mordred : {age : 16,breed : "British Shorthair" },};cats .boris ;
Pick<Type, Keys>
リリース済み
2.1
Type
からプロパティの集合Keys
(文字列リテラルまたは文字列リテラルのユニオン)を選択して型を構築します。
例
tsTry
interfaceTodo {title : string;description : string;completed : boolean;}typeTodoPreview =Pick <Todo , "title" | "completed">;consttodo :TodoPreview = {title : "Clean room",completed : false,};todo ;
Omit<Type, Keys>
リリース済み
3.5
Type
からすべてのプロパティを選択し、次にKeys
(文字列リテラルまたは文字列リテラルのユニオン)を削除して型を構築します。Pick
の反対です。
例
tsTry
interfaceTodo {title : string;description : string;completed : boolean;createdAt : number;}typeTodoPreview =Omit <Todo , "description">;consttodo :TodoPreview = {title : "Clean room",completed : false,createdAt : 1615544252770,};todo ;typeTodoInfo =Omit <Todo , "completed" | "createdAt">;consttodoInfo :TodoInfo = {title : "Pick up kids",description : "Kindergarten closes at 5pm",};todoInfo ;
Exclude<UnionType, ExcludedMembers>
リリース済み
2.8
UnionType
から、ExcludedMembers
に代入可能なすべてのユニオンメンバーを除外して型を構築します。
例
tsTry
typeT0 =Exclude <"a" | "b" | "c", "a">;typeT1 =Exclude <"a" | "b" | "c", "a" | "b">;typeT2 =Exclude <string | number | (() => void),Function >;typeShape =| {kind : "circle";radius : number }| {kind : "square";x : number }| {kind : "triangle";x : number;y : number };typeT3 =Exclude <Shape , {kind : "circle" }>
Extract<Type, Union>
リリース済み
2.8
Type
から、Union
に代入可能なすべてのユニオンメンバーを抽出して型を構築します。
例
tsTry
typeT0 =Extract <"a" | "b" | "c", "a" | "f">;typeT1 =Extract <string | number | (() => void),Function >;typeShape =| {kind : "circle";radius : number }| {kind : "square";x : number }| {kind : "triangle";x : number;y : number };typeT2 =Extract <Shape , {kind : "circle" }>
NonNullable<Type>
リリース済み
2.8
Type
からnull
とundefined
を除外して型を構築します。
例
tsTry
typeT0 =NonNullable <string | number | undefined>;typeT1 =NonNullable <string[] | null | undefined>;
Parameters<Type>
リリース済み
3.1
関数型Type
のパラメータで使用される型からタプル型を構築します。
オーバーロードされた関数の場合、これは*最後の*シグネチャのパラメータになります。 条件型内での推論を参照してください。
例
tsTry
declare functionf1 (arg : {a : number;b : string }): void;typeT0 =Parameters <() => string>;typeT1 =Parameters <(s : string) => void>;typeT2 =Parameters <<T >(arg :T ) =>T >;typeT3 =Parameters <typeoff1 >;typeT4 =Parameters <any>;typeT5 =Parameters <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T6 =Parameters <string >;typeType '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'.T7 =Parameters <>; Function
ConstructorParameters<Type>
リリース済み
3.1
コンストラクタ関数型の型からタプル型または配列型を構築します。すべてのパラメータ型(またはType
が関数でない場合は型never
)を持つタプル型を生成します。
例
tsTry
typeT0 =ConstructorParameters <ErrorConstructor >;typeT1 =ConstructorParameters <FunctionConstructor >;typeT2 =ConstructorParameters <RegExpConstructor >;classC {constructor(a : number,b : string) {}}typeT3 =ConstructorParameters <typeofC >;typeT4 =ConstructorParameters <any>;typeType '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'.T5 =ConstructorParameters <>; Function
ReturnType<Type>
リリース済み
2.8
関数Type
の戻り値の型で構成される型を構築します。
オーバーロードされた関数の場合、これは最後のシグネチャの戻り値の型になります。「条件型内での推論」を参照してください。
例
tsTry
declare functionf1 (): {a : number;b : string };typeT0 =ReturnType <() => string>;typeT1 =ReturnType <(s : string) => void>;typeT2 =ReturnType <<T >() =>T >;typeT3 =ReturnType <<T extendsU ,U extends number[]>() =>T >;typeT4 =ReturnType <typeoff1 >;typeT5 =ReturnType <any>;typeT6 =ReturnType <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T7 =ReturnType <string >;typeType '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'.T8 =ReturnType <>; Function
InstanceType<Type>
リリース済み
2.8
Type
内のコンストラクター関数のインスタンス型で構成される型を構築します。
例
tsTry
classC {x = 0;y = 0;}typeT0 =InstanceType <typeofC >;typeT1 =InstanceType <any>;typeT2 =InstanceType <never>;typeType 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.T3 =InstanceType <string >;typeType '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'.T4 =InstanceType <>; Function
ThisParameterType<Type>
リリース済み
3.3
関数型のthis
パラメーターの型を抽出します。関数型にthis
パラメーターがない場合は、unknownになります。
例
tsTry
functiontoHex (this :Number ) {return this.toString (16);}functionnumberToString (n :ThisParameterType <typeoftoHex >) {returntoHex .apply (n );}
OmitThisParameter<Type>
リリース済み
3.3
Type
からthis
パラメーターを削除します。Type
に明示的に宣言されたthis
パラメーターがない場合、結果は単純にType
になります。それ以外の場合は、this
パラメーターのない新しい関数型がType
から作成されます。ジェネリックは消去され、最後のオーバーロードシグネチャのみが新しい関数型に伝播されます。
例
tsTry
functiontoHex (this :Number ) {return this.toString (16);}constfiveToHex :OmitThisParameter <typeoftoHex > =toHex .bind (5);console .log (fiveToHex ());
ThisType<Type>
リリース済み
2.3
このユーティリティは、変換された型を返しません。代わりに、コンテキスト上のthis
型のマーカーとして機能します。このユーティリティを使用するには、noImplicitThis
フラグを有効にする必要があることに注意してください。
例
tsTry
typeObjectDescriptor <D ,M > = {data ?:D ;methods ?:M &ThisType <D &M >; // Type of 'this' in methods is D & M};functionmakeObject <D ,M >(desc :ObjectDescriptor <D ,M >):D &M {letdata : object =desc .data || {};letmethods : object =desc .methods || {};return { ...data , ...methods } asD &M ;}letobj =makeObject ({data : {x : 0,y : 0 },methods : {moveBy (dx : number,dy : number) {this.x +=dx ; // Strongly typed thisthis.y +=dy ; // Strongly typed this},},});obj .x = 10;obj .y = 20;obj .moveBy (5, 5);
上記の例では、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には型システム内の文字列操作に使用できる一連の型が含まれています。これらは、テンプレートリテラル型のドキュメントで確認できます。