Typescript:为什么 Partial 接口(interface)不接受额外的字段?

标签 typescript

interface User {
  name: string;
  age: number;  
}

let user: Partial<User> = {name: 'John', address: '123 Main st.'}

所以 typescript 会提示 address接口(interface) User 中不存在。 我的理解是只要Partial<User>是右侧对象的子集,它应该是有效的强制转换。如何正确理解?

最佳答案

这称为多余属性检查

来自 typescript 文档(https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks):

... TypeScript takes the stance that there’s probably a bug in this code. Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error.

Getting around these checks is actually really simple. The easiest method is to just use a type assertion:

关于Typescript:为什么 Partial 接口(interface)不接受额外的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54542019/

相关文章:

javascript - 检索 Post Request 响应并将其存储到 Angular 8 中的变量中

javascript - 如何将图像添加到expo中的android可绘制资源而不运行expo prebuild来创建android文件夹

class - 使用来自不同文件的类导出 TypeScript 模块

angular - 如何按特定顺序运行测试 - Playwright YAML 文件

javascript - Controller 不会在没有重播的情况下返回结果。使用 fastify 平台发送

reactjs - 此表达式不可调用。 '{}' 类型没有调用签名。 TS2349

javascript - TypeScript 自动将类型转换为整数

typescript - 如何在 TypeScript 中获取属性名和类名

typescript - 了解如何调用 REST Api 并在 Angular 2 中显示来自响应的数据

typescript /ESLint 错误 : Unable to resolve path to module 'aws-lambda' import/no-unresolved