【问题标题】:Forcing an optional interface property to be defined强制定义一个可选的接口属性
【发布时间】:2018-08-29 21:40:20
【问题描述】:

假设我有以下界面:

interface Example {
    optionalString?: string
    // ... other props
}

我有一个以Example 作为参数的函数。我知道返回类型的语法是假的。

function ensureDefined (example : Example) : Example & {optionalString: string}

此函数的想法是确保定义example 的属性optionalString 并返回该对象。在这种情况下,每次我想访问optionalString 属性时,我都不需要if(example.optionalString){}

我尝试过像这样创建界面的扩展:

interface ExampleExtension extends Example {
    optionalString: string // notice no '?'
    // ... other props
}

但是这个是不能分配回具有基本接口类型的变量的。

我是否过于复杂了?我应该只有两个不同类型的独立变量吗?

【问题讨论】:

    标签: javascript typescript interface optional


    【解决方案1】:

    接口扩展适用于我on the playground。如果它仍然不适合您,请添加足以重现问题的代码。

    【讨论】:

    • 看来你是对的。不知道我以前在做什么!
    • 有什么办法可以内联扩展接口,尽管在这种情况下是在函数的返回签名中?
    • 你最初使用的 Example & {optionalString: string} 语法对我有用。
    • 我相信 & 运算符是一个交集,因此在这种情况下可以工作(因为它只是需要的交集)。这将只允许返回符号左右共同的属性。
    • & 表示 类型 的交集,而不是属性集:A & B 是类型为 A 和类型 @987654327 的对象的类型@。任何此类对象都必须具有AB 的属性的union
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2015-04-17
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    相关资源
    最近更新 更多