問題を再現する最小限のコード ts

type X = "A" | "B";
const f = (x: X): X => (x);
const a: "A" = f("A");  // error

エラー

  • Type ‘X’ is not assignable to type ‘“A”‘.
    • Type ‘“B”’ is not assignable to type ‘“A”’

解決方法 ts

const f = <T extends X>(x: T): T => (x);
const a: "A" = f("A");  // ok

ジェネリクス TypeScript Using Type Parameters in Generic Constraints