TypeScript 函数返回一组函数

mar*_*ark 6 signature typescript

我正在尝试将以下 vanilla JS 代码移植到 TypeScript 以更好地定义所有函数的返回类型。此代码导出单个函数resource. 当被调用时,resource返回一个包含其他函数的对象。

使用Demo类中的资源时,类型签名似乎消失了,在构造函数中初始化。一种方法是为resource. 但是,如果resource 不重复已经在doThingOne()和 中定义的参数,我似乎无法定义接口doThingTwo()。我目前的尝试都让我不得不复制签名。我应该如何处理这个以保持干燥?

function resource(someVar) {

    function doThingOne(p1 = '') {
        return Promise.resolve('thing one ' + someVar + p1);
    }

    function doThingTwo(p1 = '') {
        return Promise.resolve('thing two ' + someVar + p1);
    }

    return {
        doThingOne,
        doThingTwo
    };
}

class Demo {
    resource1;

    constructor() {
        this.resource1 = resource('resource1');
    }
}

const issues = new Demo();
issues.resource1 // no type information for resource1
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 2

您基本上希望将成员键入为函数的结果类型。

最简单的方法是让编译器根据赋值来推断它:

class Demo {
    constructor(name: string, public resource1 = resource(name)) {

    }
}

const issues = new Demo("resource1");
issues.resource1 // correct type
Run Code Online (Sandbox Code Playgroud)

如果这不切实际,您可以通过以下两种方式之一获取返回类型:

在打字稿 2.8 中

使用ReturnType<T>条件类型。(2.8 在撰写本文时尚未发布,但将于 2018 年 3 月发布,您可以通过获取npm install -g typescript@next

class Demo {
    public resource1: ReturnType<typeof resource>
    constructor() {

    }
}
Run Code Online (Sandbox Code Playgroud)

2.8 之前

您可以使用辅助函数和虚拟变量从函数中提取类型:

// Dummy function, just used to extract the result type of the function passed as the argument
function typeHelper<T>(fn: (...p:any[]) => T): T{
    return null as T;
}
// Dummy variable, null at runtime, but it's type is inferred as the result of the `resource function
let dummy = typeHelper(resource);

// Create a type definition based on the type of dummy
type resourceReturnType = typeof dummy;


class Demo {
    public resource1: resourceReturnType
    constructor() {

    }
}
Run Code Online (Sandbox Code Playgroud)