LoginSignup
0
0

More than 1 year has passed since last update.

TypeScript勉強会第4回(2022/02/21) 組み込みの型関数

Last updated at Posted at 2022-02-21

初回 => https://qiita.com/KuwaK/items/b5de29fe21af3724f316

TypeScriptには組み込みで使える便利な型関数がいくつかあります。
すべての組み込みの型関数の一覧は以下にありますが、よく使う便利なものだけ紹介します。
https://www.typescriptlang.org/docs/handbook/utility-types.html

NonNullable

指定された型から、nullやundefinedを取り除いた型を返します

type T0 = NonNullable<string | number | undefined>;
// => string | number

type T1 = NonNullable<string[] | null | undefined>;
// => string[]

Pick

指定された型から、指定した名前のメンバのみを抜き出した新しいObjectの型を返します。

type = Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;
// => TodoPreview = {
//     title: "Clean room",
//     completed: false,
//    };

Omit

Pickの逆で、指定された型から指定された名前のメンバを取り除いた新しい型を返します

type Todo = {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}

type TodoPreview = Omit<Todo, "description">;

// => {
//   title: "Clean room",
//   completed: false,
//   createdAt: 1615544252770,
// };

Partial

指定した型のメンバをすべてOptionalな型(存在しない可能性があるメンバ)に変換します。
デフォルト値が設定された関数の引数の型などに使用する場合が多いです

type Todo =  {
  title: string;
  description: string;
}

type PartialTodo = Partial<Todo>
// => {
//     title?: string;
//     description?: string;
//    }

Required

Partialの逆で、すべてのメンバを必須メンバに変換します。デフォルト値が設定された関数の引数をその関数内で呼び出したときなどは Required<Aargs> な型になっていることが多いです。

type Props = {
  a?: number;
  b?: string;
}

type RequiredProp = Required<Props> 
// => {
//      a: number;
//      b: string;
//    };

Record

Record型は任意の型のキーを持つObjectの型を返します。 Record<string, 任意の型> で、その型の連想配列の型付をすることができます。


type User = {
  id; string
  name: string
  age: number
}

Record<string, User>
// => {
//      1: user1,
//      2: user2
//      ...
//    }

同じように連想配列を表す型に {[key in string]:任意の型} という、Mapped Typesを使った書き方がありますが、ちょっと読みにくいので、特に理由がなければ、Record を使ったほうが良いと思います。

Parameters

指定した関数の引数の型をタプル型で返します。(配列ではないことに注意)


type T0 = Parameters<() => string>;
// => []

type T1 = Parameters<(s: string) => void>;
// => [s: string]

type T2 = Parameters<<T>(arg: T) => T>;
// => [arg: unknown]

type F1 = (arg: { a: number; b: string }) => void;
type T3 = Parameters<F1>;
// => [arg: {
//      a: number;
//      b: string;
//    }]

ReturnType

指定した関数の返り値の型を返します。


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 F1 = () => { a: number; b: string };
type T4 = ReturnType<typeof F1>;     
// type T4 = {
//   a: number;
//   b: string;
// }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0