【发布时间】: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