Search code examples
typescripterror-handlingtype-inferencenarrowing

Assert inferred type in TypeScript


I'm looking for a nice way to assert the type TypeScript inferred for a particular variable. This is what I am using right now:

function assertType<T>(value: T) { /* no op */ }

assertType<SomeType>(someValue);

This is particularly useful when I want to make sure I cover all possible values returned by a function. For instance:

function doSomething(): "ok" | "error" { ... }

const result = doSomething();

if(result === "error") { return; }

assertType<"ok">(result);

// do something only if result is OK

This ensures that adding new variants to the sum "ok" | "error", like "timeout", will trigger a type error.

The assertType solution works in practice, but I find it unfortunate to have a noop call, and I'm hoping there may be a native way to do this, for instance:

if(result === "error") { return; }

<"ok">result // magic

// do something only if result is OK

Solution

  • use satisfies keyword to ensure the type is correct:

    function check(result: "error" | "ok") {
      if (result === "error") { return; }
    
      result satisfies "ok"
    
    }
    
    function check2(result: "error" | "ok" | "warning") {
      if (result === "error") { return; }
    
      result satisfies "ok" // ERROR here
    
    }