Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method:
function assertType<T>(value: T) { /* no op */ }
assertType<SomeType>(someValue);
This technique proves useful when ensuring all potential values returned by a function are covered. For example:
function doSomething(): "ok" | "error" { ... }
const result = doSomething();
if(result === "error") { return; }
assertType<"ok">(result);
// execute specific actions only if the result is OK
By implementing this, any addition of new variants to the sum
"ok" | "error"
, such as "timeout"
, will immediately trigger a type error.
The use of assertType
does serve its purpose practically, yet I wish to find an alternative to avoid having a redundant call, perhaps through a built-in solution like so:
if(result === "error") { return; }
<"ok">result // magic
// execute specific actions only if the result is OK