假设我有以下界面:
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/