最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Define return type based on input values - Stack Overflow

programmeradmin1浏览0评论

I'm trying to to connect to a 3rd party function, which will return an object typed as any, but its return type is actually known based on the param outputParams passed into it.

As an example:

interface OutputParam {
  name: string;
}

// This function is external and out of my control - no changes can be made to this method
const executeStoredProc = (outputParams: OutputParam[]): object => {
  const retval = {};
  for (let output of outputParams) {
    retval[output.name] = 'sample data';
  }
  return retval;
}

const example = () => {
  const outputParams: OutputParam[] = [
    { name: "Sandwich_ID" },
    { name: "Sandwich_Has_Ketchup" },
  ];

  const exampleResult = executeStoredProc(outputParams);

  // !!! GOAL: exampleResult should recognize that `Sandwich_ID` and
  // `Sandwich_Has_Ketchup` are valid properties of exampleResult
  const sandwichId = exampleResult.Sandwich_ID;
  const sandwichHasKetchup = exampleResult.Sandwich_Has_Ketchup;

  return {
    sandwichId,
    sandwichHasKetchup,
  };
};

In the example above, is there any way for me to cast the exampleResult object to the type I expect it to be based on the output params? With the example above, that type would look like:

type exampleOutput {
  Sandwich_ID: unknown,
  Sandwich_Has_Ketchup: unknown,
}
发布评论

评论列表(0)

  1. 暂无评论