Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type should I use for empty object?

Tags:

typescript

I set the return type of the function below to {}, and eslint gave an error(Don't use {} as a type. {} actually means "any non-nullish value".).

OK, I understood what this error means because return type {} allows me to return a value of other types.

So if I want to return only an empty object, what type should be used as the return type?

function a(): {} {
  return {};
  // return 1; // NOT ALLOWED
}
like image 402
devvvmannn Avatar asked Nov 14 '25 17:11

devvvmannn


1 Answers

Here you can make use of the never type.

never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns.

So here with the EmptyObject type it is saying that all properties can only be never.

No type is assignable to never so creating an object would not be possible which causes the object to be empty.

EDIT:

Not sure what is the use case for this though.

type EmptyObject = {
    [K in never] : never
}

function a(): EmptyObject {
  return {};
}

like image 75
yudhiesh Avatar answered Nov 17 '25 08:11

yudhiesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!