要求 TypeScript 具有三个属性中的确切两个。

huangapple go评论66阅读模式
英文:

Require exactly two of three properties with TypeScript

问题

我有一些React组件,需要精确地有三个属性中的两个来表示时间范围:fromtoduration。任何两个属性的组合都足以正确推导出第三个属性。因此,我希望TypeScript强制要求确切需要两个这些属性。

我尝试定义props如下:

type RangeProps =
  | {
      from: Date
      to: Date
    }
  | {
      from: Date
      duration: number
    }
  | {
      duration: number
      to: Date
    }

但是当我提供了这三个属性 (<Range from={startDate} duration={duration} to={endDate} />),TypeScript没有抱怨。如何让它抱怨呢?

英文:

I have a few React components that need exactly two of three props to represent a time range: from, to, or duration. Any combination of two is enough to derive the third one correctly. So I want TypeScript to enforce that exactly two of these props is required.

I tried defining props like this:

type RangeProps =
  | {
      from: Date
      to: Date
    }
  | {
      from: Date
      duration: number
    }
  | {
      duration: number
      to: Date
    }

But when I supply all three props (&lt;Range from={startDate} duration={duration} to={endDate} /&gt;, TypeScript doesn't complain. How can I get it to complain?

答案1

得分: 2

You can use the type never, this type means that the property cannot be passed:

type RangeProps =
  | {
      from: Date;
      to: Date;
      duration?: never;
    }
  | {
      from: Date;
      duration: number;
      to?: never;
    }
  | {
      duration: number;
      to: Date;
      from?: never;
    };
英文:

You can use the type never, this type means that the property cannot be passed:

type RangeProps =
  | {
      from: Date;
      to: Date;
      duration?: never;
    }
  | {
      from: Date;
      duration: number;
      to?: never;
    }
  | {
      duration: number;
      to: Date;
      from?: never;
    };

答案2

得分: 1

以下是您要翻译的内容:

playground
use this generic trick T extends never? T : some type check logic
T extends any? some type check logic : never also work

英文:

要求 TypeScript 具有三个属性中的确切两个。
playground

use this generic trick T extends never? T : some type check logic

T extends any? some type check logic : never also work

huangapple
  • 本文由 发表于 2023年6月6日 08:23:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定