0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptの型ガード関数がなぜ必要か

Last updated at Posted at 2025-02-08

TypeScriptの型ガード関数とは?

型ガード関数は、TypeScriptで 変数の型を特定の型に絞り込む(Narrowing) ための関数。

結論

✅ 型ガード関数 (value is 型) を使うと、TypeScriptが if 文の中で型を確定できる
boolean を返す関数では型を絞り込めない。これはTypeScript の型システムの設計上の仕様。

❌ 型エラーの例

type CommonProps = FooProps | BarProps;

type FooProps = { id: string; type: 'foo' };
type BarProps = { id: string; type: 'bar' };

let foo: string = 'foo';

const args: CommonProps = {
  id: 'id',
  blockType: foo  // ❌ エラー:string型を代入できない
};

TypeScriptは foo の型を string と認識するため、型エラーになる。


✅ 型ガード関数で解決

function isValidBlockType(value: string): value is 'foo' | 'bar' {
  return value === 'foo' || value === 'bar';
}

if (isValidBlockType(foo)) {
  const args: CommonProps = {
    id: 'id',
    blockType: foo  // ✅ エラーなし!
  };
}

value is 型 を使うと、TypeScriptは true の場合に型を確定できる


boolean を返す関数ではダメな理由

function checkBlockType(value: string): boolean {
  return value === 'foo' || value === 'bar';
}

if (checkBlockType(foo)) {
  const args: CommonProps = {
    id: 'id',
    blockType: foo  // ❌ エラー発生
  };
}

TypeScriptは 関数の内部ロジックを解析しない ため、型を絞り込めない。
TypeScript の型解析(型推論エンジン)が関数の内部ロジックを解析しないためであり、これは TypeScript の型システムの設計上の仕様。型チェック(type checker)の制約。
今後、その仕様が変われば関数の内部ロジックを解析して型を判別するようになり、型ガード関数は不要になるかも。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?