【发布时间】:2021-04-28 02:12:44
【问题描述】:
我想实现以下(在 React/TypeScript (.tsx) 中)
Main.tsx(编辑:botCommands 是一个数组,其中可以包含多个对象(command 和 botResponse())
function Main() {
return (
<TestComponent
botVariables={{
tasks: [],
groups: []
}}
botCommands={[
{
command: "-help",
botResponse(botVariables) {
return botVariables.tasks[0]
}
}
]}
/>
);
}
TestComponent.tsx
interface BotCommand {
command: string;
botResponse(botVariables: any): string;
}
interface TestComponentProps {
botVariables: any;
botCommands: BotCommand[];
}
export default function TestComponent(props: TestComponentProps) {
return (
// magic
);
}
在Main.tsx 我希望在函数botResponse() 中自动调整类型(当前为any)。这样botVariables 的内容就会自动作为类型。
简单地说,如果我在botResponse() 函数“botVariables”中写入Main.tsx。
IDE 可以向我建议 tasks 和 groups。 botVariables 中的数据可以更改,因此您不能只在 TestComponent.tsx 文件中创建接口。
我尝试过使用 typescript 泛型,但不幸的是失败了。感谢您的帮助!
【问题讨论】:
-
botVariables的约束是什么?它总是具有属性tasks和groups的对象,它们是数组吗?tasks数组的内容是否不同,或者它们总是string?
标签: javascript reactjs typescript typescript-generics