【问题标题】:Compile time check if typescript interface has one or more properties编译时检查 typescript 接口是否具有一个或多个属性
【发布时间】:2020-11-14 16:08:38
【问题描述】:

我需要找到一种方法来检查打字稿界面是否具有一个或多个属性(属性名称未知)在编译时 .

因此例如给出以下定义:

export type Cat = {};
export type Dog = { barking: boolean };

我需要一个conditional type HasAnyProperties<T>,它将给我:

type catHasProperties = HasAnyProperties<Cat>;   // false   (because Cat is {})
type dogHasProperties = HasAnyProperties<Dog>;   // true    (because Dog has one or more properties)

明确我不想要

这似乎是一个奇怪的请求,但我实际上在做的是首先filtering a type,然后我需要知道是否有任何剩余。然后,我使用该值选择性地在映射类型上添加新属性。但这是最简单的部分!

以下尝试无效:

// This always returns true
type HasAnyProperties<T> = T extends { [key: string]: any } ? true : false;

如果我知道属性的名称会容易得多,但我不知道。

如果这可能,我的猜测是它看起来像RequireAtLeastOne

【问题讨论】:

    标签: typescript conditional-types


    【解决方案1】:

    原来就是这么简单:

     export type HasAnyProperties<T> = {} extends T ? false : true;
    

    至少对我来说是这样。如果有类似需求的人发现此问题,请发表评论或添加新答案。

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 2022-01-26
      • 2019-04-03
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多