相关疑难解决方法(0)

接口在用作函数的返回类型时允许额外的属性

当接口通过类型指定为函数的返回时,它似乎接受额外的属性。

例如,如果我有一个名为 的空接口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

5
推荐指数
1
解决办法
822
查看次数

标签 统计

typescript ×1