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

标签 typescript

为什么具有可选属性的接口(interface)与不具有可选属性的接口(interface)的处理方式不同?如果没有明确定义可选的属性,是否所有属性都被认为是类型断言的可选属性?

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;

最佳答案

这是因为如果 A 可分配给 B 或 B 可分配给 A(简化说明),则类型 A 和 B 之间的类型断言会成功。

在您的情况 1 中,这些条件都不成立。但在情况 B 中,其中一个条件成立(因此断言编译正常)。

更多

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

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

关于Typescript 类型断言 - 与可选成员的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38692188/

相关文章:

reactjs - 情感风格不是压倒一切的组件

TypeScript:返回扩展 Record<string, string> 的通用类型的函数

angular - RxJS 的行为不符合预期

javascript - 将 Jest 导入常规文件

javascript - "Only entities in this entityManager may be saved"当删除 Breeze 实体时订阅了entityChanged事件处理程序

javascript - 如何逐行读取angular2上的csv文件

javascript - Angular 2 - 如何在 addEventListener 处理函数中调用 typescript 函数?

typescript - 从接口(interface)属性中删除 null

TypeScript 映射类型值取决于键

typescript - 找不到模块 : Error: Can't resolve './app/app.module.ngfactory'