[英]How can infer types from either string or string array property
鉴于以下情况:
type Action =
| { type: 'FOO' }
| { type: 'BAR' }
type Rule = {
target: string | string[],
consequence: (action:Action) => void
}
const rule1:Rule = {
target: 'FOO',
consequence: action => console.log(action) // { type: 'FOO' }
}
const rule2:Rule = {
target: ['FOO', 'BAR'],
consequence: action => console.log(action) // { type: 'FOO' } | { type: 'BAR' }
}
动作可以被分派(例如使用 redux)并且规则可以对其做出反应。 当目标与action.type匹配时,结果将使用匹配的操作执行。
我希望规则结果推断出正确的类型。 这可以由目标以某种方式完成。 但我不知道怎么做。 我目前的做法:
type Rule<Action> = {
target: string | string[],
consequence: (action:Action) => void
}
const rule:Rule<{ type: 'FOO' }> = ...
但我需要一种可以写作的方式
const rule:Rule<{ type: 'FOO' } | { type: 'BAR' }> = ...
并且规则目标推断出正确的类型
这是我能想到的最好的。 您必须放弃target
作为单个值,并依赖它始终是一个数组,即使该数组只有一个元素。 可能有办法让它与 function 过载一起工作,但我无法让它工作。
type ActionType = "FOO" | "BAR";
type Action<T extends ActionType> = { type: T };
function createRule<T extends ActionType[]>(target: T) {
return {
target,
consequence: (action: Action<T[number]>) => console.log(action)
};
}
const foo = createRule(["FOO"]);
const bar = createRule(["FOO", "BAR"]);
foo.consequence({ type: "FOO" });
foo.consequence({ type: "BAR" }); // nope
bar.consequence({ type: "FOO" });
bar.consequence({ type: "BAR" });
bar.consequence({ type: "BAZ" }); // nope
https://codesandbox.io/s/dawn-wildflower-03cbq?file=/src/index.ts
使用 function 创建规则使您可以使用 generics 而无需在每次创建新规则时将其指定为类型和值来重复自己。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.