可怕的标题,我知道!我不知道如何简明扼要地描述这一点。
我正在尝试创建一个函数,它接受一组对象,每个对象都有一个“类型”字段,以及一组处理各种类型的函数。
下面的代码是我尝试做的事情:
您可以在对处理程序的调用中看到我试图描述的对象。
type Foo = {type: "foo", name: string}
type Bar = {type: "bar", score: number}
type Props<T extends {type: string}> = {
variables: T[];
functions: {
[k in T["type"]]: (args: T) => void;
}
}
function handler<T extends {type: string}>({variables, functions}: Props<T>) {
variables.forEach(v => {
functions[v.type](v);
// ^^^^^^^^^^^^^
// No index signature with a parameter of type 'string' was found on type '{ [k in T["type"]]: (args: T) => void; }'.
})
}
handler({
variables: [{type: "foo", name: ""}, {type: "bar", score: 0}],
functions: {
"foo": (args) => {args.name}, // <--- args has type Foo | Bar, ideally would just be Foo
"bar": (args) => {args.score},
}
})
我不确定我哪里出错了,任何帮助将不胜感激。
答案 0 :(得分:0)
您可以在 Props 类型定义中将键设置为字符串
type Props<T extends {type: string}> = {
variables: T[];
functions: {
[k in T["type"] as string]: (args: T) => void;
}
}
但是,您已经注意到您没有在代码中使用 Foo 和 Bar 类型。 如下使用它们会引发错误,表明您的设计存在问题。
type Foo = {type: "foo", name: string}
type Bar = {type: "bar", score: number}
type Props<T extends {type: string}> = {
variables: T[];
functions: {
[k in T["type"] as string]: (args: T) => void;
}
}
function handler<T extends {type: string}>({variables, functions}: Props<T>) {
variables.forEach(v => {
functions[v.type](v);
})
}
handler<Foo | Bar>({
variables: [{type: "foo", name: ""}, {type: "bar", score: 0}],
functions: {
"foo": (args:Foo) => {args.name}, // <--- error here as name is not in Bar
"bar": (args:Bar) => {args.score}, // <--- error here as name is not in Foo
}
})
我建议改变你对道具的定义