LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript】typeof, keyofとその併用について

Posted at

開発中のアプリで使用していて、型を安全に使用する点で非常に便利だと思ったので簡単にまとめました。

typeof

typeofは値を型に変換するもので、変数に対して使用されます。

const evaluation = {
 good: 'Good',
 bad: 'Bad'
} as const;

const ngCase1: typeof evaluation = 'test'; // NG
// Type 'string' is not assignable to type '{ readonly good: "Good"; readonly bad: "Bad"; }'
const ngCase2: typeof evaluation = { good: 'Good' }; // NG
// Property 'bad' is missing in type '{ good: "Good"; }' but required in type '{ readonly good: "Good"; readonly bad: "Bad"; }'.

const okCase: typeof evaluation = { good: 'Good', bad: 'Bad' }; // OK

keyof

keyofはオブジェクト型のプロパティ名を取得するもので、に対して使用されます。

type evaluation = {
 good: string,
 bad: string
}

const ngCase1: keyof evaluaton = 'test'; // NG
// Type '"test"' is not assignable to type 'keyof evaluaton'.
const ngCase2: keyof evaluaton = {
 good: 'Good',
 bad: 'Bad'
}; //NG
// Type '{ good: string; bad: string; }' is not assignable to type 'keyof evaluaton'.

const okCase1: keyof evaluaton = 'good'; // OK
const okCase2: keyof evaluation = 'bad'; // OK

typeof と keyof の併用

下記のように使用すると、あるオブジェクトのプロパティ名の文字しか代入できなくなり、安全な代入が可能となります。

const evaluation = {
 good: 'Good',
 bad: 'Bad'
} as const;

const okCase1: keyof typeof evaluation = 'good'; // OK
const okCase2: keyof typeof evaluation = 'bad'; // OK

const ngCase1: keyof typeof evaluation = 'Good'; // NG
// Type '"Good"' is not assignable to type '"good" | "bad"'. Did you mean '"good"'?

また、次のように使用することでオブジェクトのプロパティに設定されている値しか代入ができなくなります。

const evaluation = {
 good: 'Good',
 bad: 'Bad'
} as const;

const okCase1: typeof evaluation[keyof typeof evaluation] = 'Good'; // OK
const okCase2: typeof evaluation[keyof typeof evaluation] = 'Bad'; // OK

const ngCase1: typeof evaluation[keyof typeof evaluation] = 'bad'; // NG
// Type '"bad"' is not assignable to type '"Good" | "Bad"'. Did you mean '"Bad"'?

終わりに

これ以外にも新しいオブジェクトの型を生成する時などにも使えそうで、型安全を意識する上で非常に便利なので良かったら使ってみてください。

最後まで読んでくださりありがとうございました。

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