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/