Javascript React:TypeScript泛型,从函数自动切换参数类型(函数作为道具)
我想实现以下内容(在React/TypeScript(.tsx)中) Main.tsx(编辑:Javascript React:TypeScript泛型,从函数自动切换参数类型(函数作为道具),javascript,reactjs,typescript,typescript-generics,Javascript,Reactjs,Typescript,Typescript Generics,我想实现以下内容(在React/TypeScript(.tsx)中) Main.tsx(编辑:botCommands是一个数组,其中可以包含多个对象(使用command和botResponse()) 在Main.tsx中,我希望在函数botResponse()中自动调整类型(当前any),以便自动将botVariables的内容作为类型 简单地说,如果我在botResponse()函数“botVariables”中写入Main.tsx IDE可以向我建议任务和组。botVariables中的数据
botCommands
是一个数组,其中可以包含多个对象(使用command
和botResponse()
)
在Main.tsx
中,我希望在函数botResponse()
中自动调整类型(当前any
),以便自动将botVariables
的内容作为类型
简单地说,如果我在botResponse()
函数“botVariables”中写入Main.tsx
IDE可以向我建议任务
和组
。botVariables
中的数据可以更改,因此您不能只在TestComponent.tsx
文件中创建接口
我尝试使用typescript泛型,但不幸失败。感谢帮助!欢迎来到StackOverflow社区 Typescript无法自动检测参数的类型 无论如何,您可以选择使用或 如果变量是一组有限的类型,则可以使用Union类型
interface MyObject {
tasks: string[]
}
interface BotCommand {
command: string;
botResponse: (botVariables: string | number | MyObject) => string;
}
具有泛型类型的示例
interface BotCommand {
command: string;
botResponse: <T extends unknown>(botVariables: T) => string;
}
更多信息请看一下。如果我正确理解您的需求,
botVariables
可以是任何东西,但是我们提供给TestComponent
的botVariables
和botCommands
需要相互匹配。也就是说,botResponse
函数的参数在bot中,命令的类型与botVariables
prop相同
为了做到这一点,我们将BotCommand
接口设置为通用接口,其中类型T
表示botResponse
变量的类型
interface BotCommand<T> {
command: string;
botResponse(botVariables: T): string;
}
这意味着该组件也是通用的
export default function TestComponent<T>(props: TestComponentProps<T>) {...}
当您使用TestComponent
时,不需要显式声明泛型t
,因为它可以从botVariables
属性中推断出来。如果botCommands
不匹配,typescript会抱怨
在本例中:
function Main() {
return (
<TestComponent
botVariables={{
tasks: ["first"],
groups: ["something"]
}}
botCommands={[{
command: "-help",
botResponse(botVariables) {
return botVariables.tasks[0]
}
}]}
/>
);
}
为了得到正确的推断,我必须使用[“first”]
而不是空数组,因为空数组的类型为从不[]
,但我们需要字符串[]
。可以使用空数组,但必须显式设置它的类型
BOT变量的约束条件是什么?
是否总是一个具有属性任务
和组
的对象,这些属性都是数组?任务数组的内容是否不同,或者它们总是字符串
?如果我们只处理BOT命令
interfa在TestComponent
组件的上下文中,botResponse
的参数不再是unknown
,因为它们与botVariables
prop的类型相同。参数tasks:[]
例如,并不总是指定。Linda Paiste的回答帮助了我。谢谢你的帮助!
interface BotCommand<T> {
command: string;
botResponse(botVariables: T): string;
}
interface TestComponentProps<T> {
botVariables: T;
botCommands: BotCommand<T>[];
}
export default function TestComponent<T>(props: TestComponentProps<T>) {...}
export default function TestComponent<T>({ botVariables, botCommands }: TestComponentProps<T>) {
return (
<div>
<h1>Bot Output</h1>
{botCommands.map(command => (
<div>
<div>Bot recieved command {command.command}</div>
<div>Bot responded {command.botResponse(botVariables)}</div>
</div>
))}
</div>
);
}
function Main() {
return (
<TestComponent
botVariables={{
tasks: ["first"],
groups: ["something"]
}}
botCommands={[{
command: "-help",
botResponse(botVariables) {
return botVariables.tasks[0]
}
}]}
/>
);
}
(method) BotCommand<{ tasks: string[]; groups: string[]; }>.botResponse(botVariables: {
tasks: string[];
groups: string[];
}): string