我正在尝试执行以下操作:
interface RgbColor {
r: number;
g: number;
b: number;
}
function rgbToHex(r: RgbColor, g?: undefined, b?: undefined): string
function rgbToHex(r: number, g: number, b: number): string
function rgbToHex(r: number|RgbColor, g?: number, b?: number): string {
if (r instanceof Object) {
// must be RgbColor
g = r.g;
b = r.b;
r = r.r;
}
// A) r was an RgbColor and we've already set r, g, and b to numbers in the if block
// B) we're meeting the second overload and r, g, and b are all numbers
// either way we know they are all numbers now
let rHex = r.toString(16);
let gHex = g.toString(16); // ERROR: Object is possibly 'undefined'.
let bHex = b.toString(16); // ERROR: Object is possibly 'undefined'.
if (rHex.length == 1) rHex = "0" + rHex;
if (gHex.length == 1) gHex = "0" + gHex;
if (bHex.length == 1) bHex = "0" + bHex;
return "#" + rHex + gHex + bHex;
}
我在ERROR
注释指示的行中收到错误。
从javascript的角度来看,该功能很好:
function rgbToHex(r , g, b) {
if (r instanceof Object) {
g = r.g;
b = r.b;
r = r.r;
}
let rHex = r.toString(16);
let gHex = g.toString(16);
let bHex = b.toString(16);
if (rHex.length == 1) rHex = "0" + rHex;
if (gHex.length == 1) gHex = "0" + gHex;
if (bHex.length == 1) bHex = "0" + bHex;
return "#" + rHex + gHex + bHex;
}
rgbToHex({ r: 120, g: 50, b: 5 }) // "#783205"
rgbToHex(120, 50, 5) // "#783205"
我的问题是如何设置函数签名,这样它就可以正常工作,而无需进行任何转换,也无需在函数体中设置任何冗余变量。即我想避免做let gVal: number = g || (r as any).g;
.
另一种选择是将其拆分为两个函数并让一个调用另一个;但我不会用 javascript 来做这件事,所以我不得不用打字稿来做这件事似乎是错误的。
抱歉,如果这是重复的。我花了几个小时查看类似的问题,但找不到任何解决此问题的方法。