MeWrite Docs

Type 'X' is not assignable to type 'Y'

TypeScriptで型が一致しない場合に発生するコンパイルエラー

概要

Type 'X' is not assignable to type 'Y' は、TypeScriptで変数や引数に互換性のない型の値を代入しようとした場合に発生するコンパイルエラーです。TypeScriptの型システムによる静的型チェックで検出されます。

エラーメッセージ

Type 'string' is not assignable to type 'number'.
Type 'null' is not assignable to type 'string'.
Type '{ name: string; }' is not assignable to type 'User'.
  Property 'id' is missing in type '{ name: string; }' but required in type 'User'.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

原因

  1. 基本型の不一致: string、number、booleanなどの型が異なる
  2. nullやundefinedの扱い: strictNullChecksが有効な場合
  3. オブジェクト型のプロパティ不足: 必須プロパティが欠けている
  4. 配列/オブジェクトの型不一致: 要素の型が異なる
  5. ユニオン型の絞り込み不足: 型ガードがない

解決策

1. 基本型の変換

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// ❌ エラー
let num: number = "123";

// ✅ 正しい:型変換
let num: number = parseInt("123", 10);
let num: number = Number("123");

// 数値から文字列
let str: string = (123).toString();
let str: string = String(123);
let str: string = `${123}`;

2. null/undefinedを許容する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ❌ エラー
let name: string = null;

// ✅ 正しい:ユニオン型で許容
let name: string | null = null;
let name: string | undefined = undefined;

// オプショナルプロパティ
interface User {
  id: number;
  name?: string;  // string | undefined
}

3. 非nullアサーション演算子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// ❌ エラー
function greet(name: string | undefined) {
  console.log(name.toUpperCase()); // undefinedかもしれない
}

// ✅ 正しい:非nullアサーション(確実な場合のみ)
function greet(name: string | undefined) {
  console.log(name!.toUpperCase());
}

// ✅ より安全:型ガード
function greet(name: string | undefined) {
  if (name) {
    console.log(name.toUpperCase());
  }
}

4. オブジェクト型のプロパティを追加

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface User {
  id: number;
  name: string;
  email: string;
}

// ❌ エラー:emailが足りない
const user: User = {
  id: 1,
  name: "John"
};

// ✅ 正しい:全プロパティを指定
const user: User = {
  id: 1,
  name: "John",
  email: "john@example.com"
};

// ✅ Partialで全てオプショナルに
const partialUser: Partial<User> = {
  id: 1,
  name: "John"
};

5. 型ガードで絞り込む

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// ❌ エラー
function process(value: string | number) {
  return value.toUpperCase(); // numberにはtoUpperCaseがない
}

// ✅ 正しい:型ガード
function process(value: string | number) {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toString();
}

// カスタム型ガード
function isString(value: unknown): value is string {
  return typeof value === "string";
}

6. 型アサーション(キャスト)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ❌ エラー
const element = document.getElementById("app");
element.innerHTML = "Hello"; // HTMLElement | null

// ✅ 正しい:型アサーション
const element = document.getElementById("app") as HTMLElement;
element.innerHTML = "Hello";

// ✅ より安全:nullチェック
const element = document.getElementById("app");
if (element) {
  element.innerHTML = "Hello";
}

7. ジェネリクスの型パラメータ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// ❌ エラー
function identity<T>(arg: T): T {
  return arg.toString(); // TにtoStringがあるとは限らない
}

// ✅ 正しい:制約を追加
function identity<T extends { toString(): string }>(arg: T): string {
  return arg.toString();
}

// または戻り値の型を修正
function identity<T>(arg: T): T {
  return arg;
}

8. 配列の型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// ❌ エラー
const numbers: number[] = [1, 2, "3"];

// ✅ 正しい
const numbers: number[] = [1, 2, 3];
const mixed: (number | string)[] = [1, 2, "3"];

// readonlyの場合
const numbers: readonly number[] = [1, 2, 3];
// numbers.push(4); // エラー:readonlyなので変更不可

9. 関数の引数・戻り値

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// ❌ エラー
function add(a: number, b: number): string {
  return a + b; // numberを返している
}

// ✅ 正しい
function add(a: number, b: number): number {
  return a + b;
}

// コールバック関数
type Callback = (result: string) => void;

// ❌ エラー
const handler: Callback = (result: number) => {};

// ✅ 正しい
const handler: Callback = (result: string) => {
  console.log(result);
};

10. as constで厳密なリテラル型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// 型が string[] に推論される
const colors = ["red", "green", "blue"];

// 型が readonly ["red", "green", "blue"] に推論される
const colors = ["red", "green", "blue"] as const;

// オブジェクトの場合
const config = {
  env: "production",
  port: 3000
} as const;
// config.env の型は "production"(stringではない)

tsconfig.jsonの設定

1
2
3
4
5
6
7
{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true,
    "noImplicitAny": true
  }
}

TypeScript の他のエラー

最終更新: 2025-12-08