React:TypeScriptジェネリック、パラメータータイプを関数から自動切り替え(小道具としての関数)

ベネット

以下を実装したい(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.tsxbotResponse()関数「botVariables」に書き込むと。それtasksgroupsIDEによって私に提案することができます。のデータbotVariablesは変更される可能性があるため、TestComponent.tsxファイルにインターフェイスを作成するだけでは不十分です。

typescriptジェネリックを試しましたが、残念ながら失敗しました。手伝ってくれてありがとう!

かわいいパイステ

私が正しくあなたの要件を理解していた場合は、botVariables何もすることが、可能性botVariablesbotCommands、我々はに提供することをTestComponent互いに一致する必要があります。つまり、内のbotResponse関数の引数は小道具botCommandsと同じタイプbotVariablesです。

これを行うために、BotCommandインターフェイスをジェネリックTにしbotResponseます。ここで、タイプ変数のタイプを表します。

interface BotCommand<T> {
  command: string;
  botResponse(botVariables: T): string;
}

当社はTestComponentPropsまた、一般的なもので、私たちは同じ適用TbotVariablesするように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は文句を言います。TestComponentbotVariablesbotCommands

この例では:

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]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ