【问题标题】:Check that at least one interface member is non-null in typescript检查打字稿中至少一个接口成员是否为非空
【发布时间】: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


【解决方案1】:

您正在寻找Object.values:

const hasOneNonNull = (input: MyInputInterface) =>
  Object.values(input).reduce((hasNonNull, value) => hasNonNull|| value !== null, false);

您还可以利用联合类型来指定,您至少需要ab

type MyInputInterface =
  | { a: A; b: B | null; aString: string | null; }
  | { a: A | null; b: B; aString: string | null; }
  | { a: A | null; b: B | null; aString: string; }

也可以使用 Typescript 的映射类型来指定类型:

以下内容来自这个SO的回答:

interface FullMyInputInterface {
  a: A;
  b: B;
  aString: string;
}

type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]

type MyInputInterface = AtLeastOne<FullMyInputInterface>

【讨论】:

  • 这完美! Object.values 确实是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 2017-10-06
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多