当接口通过类型指定为函数的返回时,它似乎接受额外的属性。
例如,如果我有一个名为 的空接口MyInterface、一个函数的类型 :type MyFunction = () => MyInterface;和一个函数const myFunction: MyFunction = () => ({ foo: 'bar' }),它不会引发该foo属性的任何错误。
以下是一些示例:
// No 'age' property
interface Human {
name: string;
}
const human: Human = {
name: '',
age: 0 // Error
}
type HumanCreator = (name: Human['name'], age: number) => Human;
const humanCreator: HumanCreator = (name, age) => ({
name,
age // No error. Why?
});
const humanCreatorr: HumanCreator = (name, age): Human …Run Code Online (Sandbox Code Playgroud) typescript ×1