以下を実装したい(React / TypeScript(.tsx)で)
Main.tsx(edit:botCommands
は、複数のオブジェクトを(withcommand
および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
型として扱われます。
簡単に言えばMain.tsx
、botResponse()
関数「botVariables」に書き込むと。それtasks
とgroups
IDEによって私に提案することができます。のデータbotVariables
は変更される可能性があるため、TestComponent.tsx
ファイルにインターフェイスを作成するだけでは不十分です。
typescriptジェネリックを試しましたが、残念ながら失敗しました。手伝ってくれてありがとう!
私が正しくあなたの要件を理解していた場合は、botVariables
何もすることが、可能性botVariables
とbotCommands
、我々はに提供することをTestComponent
互いに一致する必要があります。つまり、内のbotResponse
関数の引数は小道具botCommands
と同じタイプbotVariables
です。
これを行うために、BotCommand
インターフェイスをジェネリックT
にしbotResponse
ます。ここで、タイプは変数のタイプを表します。
interface BotCommand<T> {
command: string;
botResponse(botVariables: T): string;
}
当社はTestComponentProps
また、一般的なもので、私たちは同じ適用T
にbotVariables
するようにbotCommands
。
interface TestComponentProps<T> {
botVariables: T;
botCommands: BotCommand<T>[];
}
これは、コンポーネントも汎用であることを意味します。
export default function TestComponent<T>(props: TestComponentProps<T>) {...}
両方props
が同じを共有するため、渡された変数から応答を作成することに問題はありません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>
);
}
ジェネリックは小道具から推測できるため、T
使用時に明示的に宣言する必要はありません。一致しない場合、typescriptは文句を言います。TestComponent
botVariables
botCommands
この例では:
function Main() {
return (
<TestComponent
botVariables={{
tasks: ["first"],
groups: ["something"]
}}
botCommands={[{
command: "-help",
botResponse(botVariables) {
return botVariables.tasks[0]
}
}]}
/>
);
}
botResponse
関数の推定署名は完全で正しいです:
(method) BotCommand<{ tasks: string[]; groups: string[]; }>.botResponse(botVariables: {
tasks: string[];
groups: string[];
}): string
適切な推論を得る["first"]
ために、空の配列はとして入力されますが、必要なため、空の配列の代わりに使用するnever[]
必要がありましたstring[]
。空の配列を使用できますが、その型を明示的に設定する必要があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加