TypeScript タプルの型推論について

TypeScriptでタプルを使う際に、型推論について注意する必要があります。

const error = [true, 'ID is not found.'];  // (boolean | string)[] 
error[0] = 'hoge'; // コンパイルエラーにはならない

上記のように、タプルの一つ目の要素はboolean, 二つ目の要素はstringとしたい場合、そのままでは error[0] に string が入れられてしまいます。

これは、error の型が (boolean | string)[] であると推論されているためです。

以下のように型を指定することで、コンパイルエラーにすることができます。

const error: [boolean, string] = [true, 'ID is not found.'];
error[0] = 'hoge'; // error[0]はbooleanではないといけないので、コンパイルエラーになる

もしくは

const error = [true, 'ID is not found.'] as [boolean, string];
error[0] = 'hoge'; // error[0]はbooleanではないといけないので、コンパイルエラーになる

ちなみに、以下のようにすることで再代入を防ぐことができます。

const error = [true, 'ID is not found.'] as const;
error[0] = 'hoge'; //再代入できないのでコンパイルエラー