【发布时间】:2021-02-14 11:05:26
【问题描述】:
我想要一个函数,我们称它为DummyService,它将接受一些definition 对象作为参数,并以这些返回函数的参数只能接受已传递的参数值的方式返回一堆函数以DummyService 作为参数。请参阅下面的代码示例。知道如何实现这一目标吗?提前非常感谢。
type Definition = {
id: string;
steps: Array<{key: string, callback?: () => void}>
};
const DummyService = (definition: Definition) => {
return {
dummyFn: (step: {key: any}) => { // I need to figure out the type that would allow to pass only certain values that has been passed in `steps` array of `definition`
console.log(step);
}
};
};
const DummyComponent1 = () => {
const definition = {
id: "testId1",
steps: [
{ key: "key1"},
{ key: "key2"},
],
};
const { dummyFn } = DummyService(definition);
const handler = () => dummyFn({ key: "key1dsfasd" }); // I want this to be invalid - valid key values should be only "key1" or "key2"
return <div onClick={handler}>test</div>;
}
const DummyComponent2 = () => {
const definition = {
id: "testId2",
steps: [
{ key: "key3"},
{ key: "key4"},
],
};
const { dummyFn } = DummyService(definition);
const handler = () => dummyFn({ key: "key3" }); // This should be valid - valid key values should be only "key2" or "key4"
return <div onClick={handler}>test</div>;
}```
【问题讨论】: