这是我的示例代码:
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
。E能够知道get()函数的返回类型直接从事实,如果我调用可选参数或没有
您想这样声明重载函数吗?
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();
Checkout this playground