What type should I use for empty object?

Viewed 4059

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
}
2 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 {};
}

You're not correct in the assumption that the typescript compiler will prevent numbers or any other primitive type to be assigned to {}.

const test1: {} = 'hello'
const test2: {} = 123
const test3: {} = false
const test4: {} = { foo: 'bar' }
const test5: {} = [1, 2, 3]
const test6: {} = null          // Error if strictNullChecks is set to true in tsconfig
const test7: {} = undefined     // Error if strictNullChecks is set to true in tsconfig

It's may also be interesting to learn the difference between object and Object: Typing objects in TypeScript

Index Signatures

type GenericObject = { [key: string]: any };

function a(): GenericObject  {
  return {};
  // return 1; // NOT ALLOWED
}

Key of all properties is any string and the type of all is any

Utility Type

There is also a broad variety of utility types for these kind of problems but I personally haven't used them.

Related