Stephen Paul
Stephen Paul

Reputation: 39005

How to define a function which cannot return anything in TypeScript

I am writing an API which has 2, very similar, functions:

function update(f: () => string) {...}
function updateDeep(f: () => void) {...}

As you can see, I am trying to make sure that the client of my API passes the correct function type depending on which function they call.

The first function, update, works as predicted. This will rightly throw a compilation error:

update(() => console.log('hey'));

The second function, updateDeep, does not throw a compilation error event though it should:

updateDeep(() => 'hey');

How to I declare a function type which does not return anything?

Upvotes: 1

Views: 1137

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220944

It isn't possible to make this happen. As the recipient of a function, your only ability is to set a lower bound on what kind function is provided.

See also the TypeScript FAQ entry: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void

Upvotes: 4

Related Questions