typescript 根据提供的参数动态设置返回类型

58wvjzkj  于 2023-03-31  发布在  TypeScript
关注(0)|答案(2)|浏览(130)

我有四个班级,如下:

class PutCommand {
   // TODO
}

class PutCommandOutput {
   // TODO
}

class DeleteCommand {
   // TODO
}

class DeleteCommandOutput {
   // TODO
}

我试图创建一个函数,它接受PutCommandDeleteCommand作为参数,然后根据参数返回PutCommandOutputDeleteCommandOutput
最初,我的功能是这样的。

function executeCommand(command: PutCommand|DeleteCommand): PutCommandOutput|DeleteCommandOutput {
   // TODO:
}

但是我仍然需要在执行函数后检查返回值的类型,如下所示:

const output = executeCommand(command);

if (output instance PutCommandOutput) {

} else {
   // DeleteCommandOutput
}

为了让它更智能,我可以把函数改成这样。

function executeCommand<T>(command: PutCommand|DeleteCommand): T {
   // TODO:
}

但我仍然需要显式地传递返回类型,如下所示:

const output = executeCommand<DeleteCommandOutput>(command);

有没有一种方法可以通过根据参数动态地改变返回类型来使函数更智能?
示例:

const output = executeCommand(putCommand); // passing the instance of PutCommand so that return type is PutCommandOutput

// here I can call all the functions of PutCommandOutput
46qrfjad

46qrfjad1#

由于缺乏信息,这是我所能做的最好的。

interface PutCommand {
  type: 'put';
  payload: any;
}

interface PostCommand {
  type: 'post';
  payload: any;
}

interface PutCommandOutput {
  type: 'put';
  body: any;
}

interface PostCommandOutput {
  type: 'post';
  body: any;
}

type ReturnCommandOutput<T> =
  T extends PutCommand ? PutCommandOutput :
  T extends PostCommand ? PostCommandOutput :
  never;

function executeCommand<T>(command: T): ReturnCommandOutput<T> {
  return {
    // ...
  } as ReturnCommandOutput<T>;
}

const putCommand: PutCommand = {
  type: 'put',
  payload: {}
}

const postCommand: PostCommand = {
  type: 'post',
  payload: {}
}

const putCommandOutput = executeCommand(putCommand);
const postCommandOutput = executeCommand(postCommand);

TSPlayground---〉这里

mefy6pfw

mefy6pfw2#

function executeCommand〈P extends PutCommand|DeleteCommand〉(命令:P):P extends PutCommand?PutCommandOutput:DeleteCommandOutput { // TODO:}
希望这对你有帮助。

相关问题