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

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

Require exactly two of three properties with TypeScript

问题

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

我尝试定义props如下:

  1. type RangeProps =
  2. | {
  3. from: Date
  4. to: Date
  5. }
  6. | {
  7. from: Date
  8. duration: number
  9. }
  10. | {
  11. duration: number
  12. to: Date
  13. }

但是当我提供了这三个属性 (<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:

  1. type RangeProps =
  2. | {
  3. from: Date
  4. to: Date
  5. }
  6. | {
  7. from: Date
  8. duration: number
  9. }
  10. | {
  11. duration: number
  12. to: Date
  13. }

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:

  1. type RangeProps =
  2. | {
  3. from: Date;
  4. to: Date;
  5. duration?: never;
  6. }
  7. | {
  8. from: Date;
  9. duration: number;
  10. to?: never;
  11. }
  12. | {
  13. duration: number;
  14. to: Date;
  15. from?: never;
  16. };
英文:

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

  1. type RangeProps =
  2. | {
  3. from: Date;
  4. to: Date;
  5. duration?: never;
  6. }
  7. | {
  8. from: Date;
  9. duration: number;
  10. to?: never;
  11. }
  12. | {
  13. duration: number;
  14. to: Date;
  15. from?: never;
  16. };

答案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:

确定