为什么 TypeScript 不抱怨由 Object.create 导致的接口违规?
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!
}
为什么 f
和 j
通过类型检查?是否可以配置 TypeScript 以便 h
通过类型检查但 f
和 j
失败?
Object.create
被 Typescript 设计为 return any
。
Typescript 的 Github 存储库中有一个 issue,但它已关闭,他们不打算很快更改它。
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!
}
为什么 f
和 j
通过类型检查?是否可以配置 TypeScript 以便 h
通过类型检查但 f
和 j
失败?
Object.create
被 Typescript 设计为 return any
。
Typescript 的 Github 存储库中有一个 issue,但它已关闭,他们不打算很快更改它。