Home > other >  Type difference between "() => void" and "() => {}"
Type difference between "() => void" and "() => {}"

Time:11-03

I'm playing with TS types, and when I define these ones:

type type1 = () => {}
type type2 = () => void

and create a variable to use the types:

const firstType: type1 = () => { }
const SecondType: type2 = () => { }

I'm getting the problem: "Type 'void' is not assignable to type '{}'" on the firstType. Why is this happening? Both are "void" functions.

CodePudding user response:

type type1 = () => {}
type type2 = () => void

The first declares a function type which returns {} i.e. the empty object

The second type is a function which returns void, i.e. nothing


In order to use the first type, you have to wrap the {} with brackets, otherwise typescript thinks you are missing a return statement

const firstType: type1 = () => ({})
const SecondType: type2 = () => { }
  • Related