[英]Typescript - How Multiple Type situation in React
type PropsType = {top: number} | {bottom: number}
// A funtion that make something run at one direction by distance.
function run(props: PropsType) {
...
}
run({top: 100})
or run({bottom: 100})
run({top: 100})
或run({bottom: 100})
not run({top: 100, bottom: 100})
(which is the current) not run({top: 100, bottom: 100})
(这是当前的)
not trigger suggtion have both props:不触发建议有两个道具:
So, how to limit the type with different situation, I don't want the props accept top
and bottom
at same time.所以,如何限制不同情况的类型,我不希望道具同时接受top
和bottom
。
You can use "never" keyword like this:您可以像这样使用“从不”关键字:
type PropsType = {top: number, bottom?: never} | {top?: never, bottom: number}
// A funtion that make something run at one direction by distance.
function run(props: PropsType) {
...
}
You can make your union more stricted:你可以让你的工会更加严格:
type PropsType = { top: number } | { bottom: number }
// credits goes to Titian Cernicova-Dragomir
//https://stackoverflow.com/questions/65805600/struggling-with-building-a-type-in-ts#answer-65805753
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> =
T extends any
? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>
// A funtion that make something run at one direction by distance.
function run(props: StrictUnion<PropsType>) {
}
run({ top: 100, bottom: 100 }) // error
run({ top: 100 }) // ok
run({ bottom: 100 }) // ok
If this line:如果这一行:
type UnionKeys<T> = T extends T ? keyof T : never;
is not clear for you, please refer to the docs你不清楚,请参考文档
When conditional types act on a generic type, they become distributive when given a union type.当条件类型作用于泛型类型时,它们在给定联合类型时变得可分配。 If we plug a union type into ToArray, then the conditional type will be applied to each member of that union.如果我们将联合类型插入 ToArray,则条件类型将应用于该联合的每个成员。
What about optional parameter?可选参数呢?
type PropsType = {top?: number, bottom?: number}
Usage will be:用法将是:
run({top: 100});
run({bottom: 100});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.