javascript - 强制定义可选的接口(interface)属性

标签 javascript typescript interface option-type

假设我有以下界面:

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
}

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

我是不是把这个问题搞得太复杂了?我应该只有两个不同类型的单独变量吗?

最佳答案

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

关于javascript - 强制定义可选的接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086442/

相关文章:

Asp.Net 和 Shadowbox

Javascript - 在弹出窗口中滚动到底部

typescript - 找不到包类型定义

javascript - 我想在注册成功时显示弹出消息,如果注册失败,则在同一页面上重定向时显示失败消息

javascript - XMLHttpRequest 访问 facebook 开发人员和图

configuration - 配置 VSCode 执行不同的任务

javascript - 排序功能未按预期工作

ios - 如何使用删除(_ :) in Swift4 to Removes the selected content from your interface?

c# - 将接口(interface)的事件从 VB.Net 转换为 C#

javascript - typescript 索引获取/设置