Type Alias CanAssign<A, B, Then, Else>

CanAssign<A, B, Then, Else>: boolean extends A
    ? boolean extends B
        ? Then
        : Else
    : A extends B
        ? Then
        : Else

Can A assign to B

Note that when union is involved, the assignability is measured distributively. Meaning the result can be Then | Else (i.e. boolean by default), instead of distinctive Then (true) or Else (false).

This is the correct behavior.

Type Parameters

  • A
  • B
  • Then = true
  • Else = false

use Assignable<A, B> instead

CanAssign<number | string, number> // boolean

We are checking can A assign to B. Since A is number | string, A can assign to B when A is number(true), andAcannot assign toBwhenA is string (false). So the result is true | false = boolean.

If you want to make sure all branches are assignable, use StrictCanAssign<A, B>.