简体   繁体   English

Typescript类型断言 - 与可选成员的接口

[英]Typescript type assertions - interface with optional members

Why interface with optional property is treated differently from interface without? 为什么与可选属性的接口与没有接口的接口区别对待? Are all the properties considered optional for type assertion if none of them defined optional explicitly? 如果没有明确定义可选项,那么所有属性都被认为是类型断言的可选属性吗?

interface WithOptionalProperty {
    requiredProperty: string;
    optionalProperty?: string;
}

//compilation error 'requiredProperty' is missing
let a = { optionalProperty: '' } as WithOptionalProperty; 

interface WithoutOptionalProperties {
    requiredProperty: string;
    anotherRequiredProperty: string;
}

//but this works as expected
let b = { anotherRequiredProperty: '' } as WithoutOptionalProperties;

This is because type assertions between types A and B succeed if A is assignable to B or B is assignable to A (simplified explanation). 这是因为如果A可分配给B或B可分配给A(简化说明),则类型A和B之间的类型断言成功。

Neither of these conditions are true in your case 1. But one of these is true in case B (hence the assertion compiles fine). 在你的情况下,这些条件都不是真的1.但是在B情况下其中一个是正确的(因此断言编译得很好)。

More 更多

https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

Double Assertion : https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html#double-assertion 双断言: https//basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html#double-assertion

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM