从可选参数更改函数 return 签名

change function return signature from optional param

这是我的示例代码:

type base = {
    a: string;
};

type base_plus = {
    foo: string;
};

const get = (param?: number) => {
    const newBase: base = { a: '1' };

    if (param) {
        return { ...newBase, foo: 'bar' } as base_plus;
    }
    return newBase;
};

我要的是这个:

const a = get(1); // => a is of type base_plus
const b = get(); // => b is of type base

即如果我使用可选参数或不使用

进行调用,能够直接从事实中知道 get() 函数的 return 类型

你想像这样声明重载函数吗?

type base = {
    a: string;
};

type base_plus = {
    foo: string;
};

function get(param: number): base_plus;

function get():base;

function get(param?: number) {
    const newBase: base = { a: '1' };

    if (param) {
        return { ...newBase, foo: 'bar' } as base_plus;
    }

    return newBase;
};

const a = get(1); // => a is of type base_plus
const b = get();

检查这个 playground