使用第一个可选参数重载
Overload with first optional parameter
如何实现以下逻辑?
function test(data: {x}, f: Function);
function test(f: Function);
function test(data: {x}, f: Function) {
if (!f) {
f = data;
data = {x: 111};
}
return f(data);
}
test({x: 17}, t => 0);
test(t => 0);
它以正确的方式编译,但显示 2 个错误。
function test(data, f) {
if (!f) {
f = data;
data = { x: 111 };
}
return f(data);
}
test({ x: 17 }, function (t) { return 0; });
test(function (t) { return 0; });
我找到了解决方案:
function test(data: {x}, f: Function);
function test(f: Function);
//function test(data: {x} | Function, f?: Function) {
function test(data, f?) {
if (!f) {
f = data as Function;
data = {x: 111};
}
return f(data);
}
以下调用都可以:
test({x: 17}, t => 0);
test(t => 0);
以下不是:
test({x: 17});
test(0);
test(t => 0, t => 0);
以下任何一种方法似乎都可以:
function test(data: {x} | Function, f?: Function) {
function test(data, f?) {
并且需要显式类型转换:
f = data as Function;
如何实现以下逻辑?
function test(data: {x}, f: Function);
function test(f: Function);
function test(data: {x}, f: Function) {
if (!f) {
f = data;
data = {x: 111};
}
return f(data);
}
test({x: 17}, t => 0);
test(t => 0);
它以正确的方式编译,但显示 2 个错误。
function test(data, f) {
if (!f) {
f = data;
data = { x: 111 };
}
return f(data);
}
test({ x: 17 }, function (t) { return 0; });
test(function (t) { return 0; });
我找到了解决方案:
function test(data: {x}, f: Function);
function test(f: Function);
//function test(data: {x} | Function, f?: Function) {
function test(data, f?) {
if (!f) {
f = data as Function;
data = {x: 111};
}
return f(data);
}
以下调用都可以:
test({x: 17}, t => 0);
test(t => 0);
以下不是:
test({x: 17});
test(0);
test(t => 0, t => 0);
以下任何一种方法似乎都可以:
function test(data: {x} | Function, f?: Function) {
function test(data, f?) {
并且需要显式类型转换:
f = data as Function;