TypeScript type predicate or throw

Viewed 16

Is there a way to write a function with type predicate that throws instead of returning false and returns void (undefined) istead of true? Something like this, which doesn't compile:

function assertString(value: unknown): value extends string ? void : never {
  if (typeof value !== 'string') {
    throw new Error('string expected');
  }
}

"boolean" version is simple, but not what I need:

function isString(value: unknown): value is string {
  return typeof value === 'string';
}
0 Answers
Related