user17732557
user17732557

Reputation:

Specify the return type of a TS arrow function as a type refinement

Is it possible to specify the return type of an arrow function as being a type refinement?

function foo(x: unknown): x is string {
  return typeof x === 'string';
}

// neither of these works
const bar = (x: unknown) => (typeof x === 'string') as x is string;
const baz = (x: unknown) => <x is string>(typeof x === 'string');

Upvotes: 1

Views: 792

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85102

The syntax for a return type of an arrow function is similar to a regular function. After the argument list, you put a colon, and then the return type:

const bar = (x: unknown): x is string => typeof x === 'string';

Playground link

Upvotes: 4

Related Questions