在TypeScript中覆盖函数返回类型

时间:2018-03-13 01:32:34

标签: typescript interface casting

我想覆盖函数的返回类型以便为其设置别名。这很容易实现,但我无法在不重新定义函数参数的情况下找到解决方案,违反DRY原则。

实际应用程序是具有从REST API返回数据的通用函数。

// this function resolves with some object (e.g. from a REST call)
function doStuff<T>(data: string): Promise<T> {
    return Promise.resolve(<any>{
        data,
        isStuff: true
    });
}

// I know `doStuff()` will resolve with an object matching this interface
interface CoolStuff {
    data: string;
    isStuff: boolean;
    isCool: boolean;
}

// I want to alias `doStuff()` to return `CoolStuff`-typed data but without restating the signature
// the `data` parameter is already present in `doStuff()`
const doCoolStuff: <T = CoolStuff>(data: string) => Promise<T> = doStuff;

doCoolStuff('data') // correct return and parameter types but not DRY

0 个答案:

没有答案