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
}
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 {};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With