Skip to content

Empty interface allow any object? #14606

Closed
@mleko

Description

@mleko

I posted question on SO but haven't received definite answer so I assume this might be a bug.

Why empty interface doesn't require object to be empty?

interface A {};
const a: A = {a: 1};
console.log(a);

is valid code and will output { a: 1 }.

I would assume that adding optional property should work fine, but

interface A {};
interface B extends A {
	b?: any;
}
const a: B = {a: 1};
console.log(a);

ends with error Type '{ a: number; }' is not assignable to type 'B'.

  • If interface define what properties object must have, B case should work fine, all required properties are present.
  • If interface define what properties object can have, A case should result in error, a is not defined in interface.

Non empty interface defines both what object can and must have.
Empty interface behaves like any.

Is there explanation why empty interface behaves like this? Is this intentional or it's just a bug?

Expected behavior:

interface A {};
const a: A = {a: 1};
console.log(a);

error Type '{ a: number; }' is not assignable to type 'A'.

Actual behavior:

interface A {};
const a: A = {a: 1};
console.log(a);

{ a: 1 }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions