javascripttypescriptprototype-chain

Why doesn't TypeScript complain about interface violations resulting from Object.create?


type Foo = {
  x: number;
};

function g(): Foo {
  return {}; // Fails type-check

  // Property 'x' is missing in type '{}' but required in type 'Foo'.
}

function f(): Foo {
  return Object.create({}); // Passes!
}

function h(): Foo {
  return Object.create({x: 0}); // Also passes
}

function j(): Foo {
  return Object.create({x: "Hi"}); // Also passes!
}

Why do f and j pass type-checking? Is it possible to configure TypeScript so that h passes type-checking but f and j fail?


Solution

  • Object.create is designed to return any by Typescript. There has been an issue in Typescript's Github repository but it's closed and they do not intend to change it soon.