英文:
Require exactly two of three properties with TypeScript
问题
我有一些React组件,需要精确地有三个属性中的两个来表示时间范围:from
、to
或duration
。任何两个属性的组合都足以正确推导出第三个属性。因此,我希望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 (<Range from={startDate} duration={duration} to={endDate} />
, 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
英文:
use this generic trick T extends never? T : some type check logic
T extends any? some type check logic : never
also work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论