0

Given the following code:

    private getJsonBody(body: {}|FormData) {
        return !(body instanceof FormData) ? JSON.stringify(body) : body;
    }

What do the open+close curly braces mean as a type? In the current environment I'm using this doesn't compile and I have to change it to any to get it to work.

Siada
  • 103
  • 1
  • 9
  • 1
    It's an object type with no known properties, also known as the "empty object type". It matches just about anything. Only `null` and `undefined` may not be assigned to it. – jcalz Aug 10 '19 at 20:02
  • So why would I get a compiler error about something like: "Object PersonViewModel cannot be assigned to type {}" (the wording may be incorrect on that, I don't have the code to hand right now) – Siada Aug 10 '19 at 20:04
  • 2
    No idea, you probably need to post a [mcve] for someone to help you. – jcalz Aug 10 '19 at 20:06
  • Possible duplicate of [Typescript empty object and any difference](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference) – jcalz Aug 10 '19 at 20:07
  • 1) You should have referenced the version of Typescript you are on. 2) [This post](https://stackoverflow.com/questions/45339065/typescript-empty-object-for-a-typed-variable) may provide an alternate solution with `Partial` – JGFMK Aug 10 '19 at 20:28

1 Answers1

1

That is an Empty Object Type.

It describes an object that has no members on its own. TypeScript issues a compile-time error when you try to access arbitrary properties on such an object:

// Type {}
const obj = {};

// Error: Property 'prop' does not exist on type '{}'.
obj.prop = "value";

However, you can still use all properties and methods defined on the Object type, which are implicitly available via JavaScript's prototype chain:

// Type {}
const obj = {};

// "[object Object]"
obj.toString();

Relevant info is Basarat's Lazy Object Initialization entry that explains how Typescript will refuse this process and how to work with it.

Using that entry you would need to change your code in this manner:

interface Foo {
  bar: string;
  baz: number;
}

private getJsonBody(body: {} as Foo | FormData) {
  return !(body instanceof FormData)
    ? JSON.stringify(body)
    : body;
}
aviya.developer
  • 3,343
  • 2
  • 15
  • 41
  • 1
    This makes sense to me - I was investigating why my openapi generated lib wasn't compiling and it's to do with the service class allowing a null request, but the HttpClient asking for {} – Siada Aug 12 '19 at 08:54