【发布时间】:2019-12-25 14:23:57
【问题描述】:
假设我有一个打字稿界面:
interface MyInputInterface {
a: A | null
b: B | null
aString: string | null
}
这是我目前拥有的:
const hasOneNonNull = (input: MyInputInterface) =>
input.a !== null || input.b !== null || input.aString !== null
但这似乎很脆弱。每次添加新的接口成员时,我都必须记住更新检查。有没有办法遍历所有接口成员并检查其中至少一个是非空的?
这样的东西会更理想(getAllMembers 是伪代码):
const hasOneNonNull = (input: MyInputInterface) =>
input.getAllMembers().find((elem: any) => any !== null) !== null
【问题讨论】:
-
如果您确定您的对象中没有其他成员,您可以使用Object.values()。
标签: typescript