LoginSignup
9
6

More than 5 years have passed since last update.

TypeScriptの keyof を特定の型でフィルタする

Posted at

TypeScriptで少しハマったのでメモ

↓のようなインタフェースがあったとして

interface Sample {
  name    : string;
  age     : number;
  email   : string;
  address : string;
  birthday: Date;
}

type Hoge = keyof Sample;
// -> name | age | email | adress | birthday

型がstringのキーだけの一覧が欲しい!となったので以下のようなTypeを使いました。

type FilteredKeys<T, U> = {
  [P in keyof T]: T[P] extends U ? P : never
}[keyof T];

type Hoge = FilteredKeys<Sample, string>;
// -> name | email | address

こんなことをしたい時点で少し無理やりな実装になってる可能性が高いですが
忘れないようにメモ

9
6
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
9
6