英文:
Typescript nested property in interface isn't required?
问题
我有一个带有嵌套对象的接口:
export interface Person {
PersonWrapper: {
name: string;
address: string
email?: string;
}
}
如果我尝试从中创建一个对象,似乎*name*不是必需的,但它应该是。它在接口中没有被定义为可选属性。这是我创建它的方式:
const payload = {
PersonObj: {
address: '123 memory lane'
}
} as Person;
为什么我没有得到编译时错误,指出*name*是必需的?如果我忘记将其包装在*PersonWrapper*中,那么我肯定会得到错误。
英文:
I've got an interface with a nested object:
export interface Person {
PersonWrapper: {
name: string;
address: string
email?: string;
}
}
If I try and create an object from it, it seems that name is not required, but it should be. It's not defined as an optional property in the interface. Here's how I create it:
const payload = {
PersonObj: {
address: '123 memory lane'
}
} as Person;
Why aren't I getting a compile-time error saying that name is required? If I forget to wrap it in PersonWrapper then I definitely get an error.
答案1
得分: 5
由于您没有使用 类型注解,而是使用 类型断言,对于编译器而言,您已经接近 Person
,因此它不会因为缺少属性而抱怨。要修复它,请改用类型注解:
// 预期错误
const payload: Person = {
PersonWrapper: {
address: "123 memory lane",
},
};
您可以在 这里 阅读有关类型注解和类型断言之间的区别。
英文:
Since you are not using type annotation but using type assertion, for the compiler, you are close enough to the Person
, thus it doesn't complain about the missing properties. To fix it, use type annotation instead:
// expected error
const payload: Person = {
PersonWrapper: {
address: "123 memory lane",
},
};
You can read more about the difference between type annotation and assertion in here
答案2
得分: 2
- 类型注解
let name: string;
- 类型断言
let name = getSomeValue() as string;
根据 TypeScript 文档,类型断言比类型注解更宽松:
TypeScript 只允许将类型断言转换为更具体或更不具体的类型版本。此规则防止了“不可能的”强制转换[...]
来源:https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions
英文:
TypeScript distinguish:
- Type Annotation
let name: string;
- Type Assertion
let name = getSomeValue() as string;
As per TypeScript document, type assertion is loose, compared to type annotation (which is stricter):
> TypeScript only allows type assertions which convert to a more specific or less specific version of a type. This rule prevents “impossible” coercions [...]
>
> SOURCE: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论