Typescript-我可以动态设置函数的返回类型吗?

Typescript-我可以动态设置函数的返回类型吗?,typescript,interface,Typescript,Interface,可以使变量baz动态地具有字符串类型吗 type exampleType = () => ReturnType<exampleType>; // I need to return the type of any function I pass (Eg. ReturnType<typeof foo>) interface IExampleInterface { bar: exampleType; } function foo(): string { ret

可以使变量baz动态地具有字符串类型吗

type exampleType = () => ReturnType<exampleType>; // I need to return the type of any function I pass (Eg. ReturnType<typeof foo>)

interface IExampleInterface {
  bar: exampleType;
}

function foo(): string {
  return 'AAAAAAA';
}
const foobar = {
  bar: foo,
} as IExampleInterface;

const baz = foobar.bar();

baz; // Baz has type "any"
type exampleType=()=>ReturnType;//我需要返回我传递的任何函数的类型(例如ReturnType)
接口IExampleInterface{
条形图:示例类型;
}
函数foo():字符串{
返回“AAAAAAA”;
}
常数foobar={
酒吧:福,
}如IESampleInterface;
const baz=foobar.bar();
baz;//Baz有“any”类型

我不清楚界面的目标是什么。这是我能得到的最接近我认为你想要的:

interface IExampleInterface<T extends () => any> {
  bar: () => ReturnType<T>;
}

function foo(): string {
  return 'AAAAAAA';
}
const foobar: IExampleInterface<typeof foo> = {
  bar: foo,
}

const baz = foobar.bar();
interface-IExampleInterface-any>{
条:()=>返回类型;
}
函数foo():字符串{
返回“AAAAAAA”;
}
常量foobar:IExampleInterface={
酒吧:福,
}
const baz=foobar.bar();

如果推断泛型是一种选择,那么foo的
类型将是多余的。

你太努力了。TypeScript具有一种称为类型推断的功能,它将免费为您执行此操作。将
作为IExampleInterface
删除,它应该“正常工作”

函数foo():字符串{
返回“AAAAAAA”;
}
常数foobar={
酒吧:福,
}
const baz=foobar.bar();
baz;//Baz具有类型“string”

请记住,这是示例代码,因此可能必须传递对象,并且在某些地方必须使用接口键入参数,并且推断的类型将丢失。(很明显,我们可以在这里删除界面)根据帐户的新程度和他们询问的短语的方式,我认为此人对TypeScript是新手。虽然你是对的,但我觉得这个答案可能更接近他们想要的。你想在这里实现什么?“as”关键字是一个类型断言。它告诉编译器将对象视为编译器推断对象的类型的另一种类型。尝试像这样声明const foobar可能是:
const foobar:IExampleInterface={…}
这是正确的答案,因为OP要求接口依赖于函数类型。但是在我看来,如果泛型T指的是返回类型而不是函数类型,那么代码读起来就更清楚了。