My objective is as follows:
interface ColorRgb {
red: number;
green: number;
blue: number;
}
function rgbToHex(red: ColorRgb, green?: undefined, blue?: undefined): string
function rgbToHex(red: number, green: number, blue: number): string
function rgbToHex(red: number|ColorRgb, green?: number, blue?: number): string {
if (red instanceof Object) {
// must be ColorRgb
green = red.green;
blue = red.blue;
red = red.red;
}
let redHex = red.toString(16);
let greenHex = green.toString(16); // ERROR: Object is possibly 'undefined'.
let blueHex = blue.toString(16); // ERROR: Object is possibly 'undefined'.
if (redHex.length == 1) redHex = "0" + redHex;
if (greenHex.length == 1) greenHex = "0" + greenHex;
if (blueHex.length == 1) blueHex = "0" + blueHex;
return "#" + redHex + greenHex + blueHex;
}
The errors are occurring on the lines mentioned by ERROR
comments.
From a JavaScript standpoint, the function appears to be correct:
function rgbToHex(red , green, blue) {
if (red instanceof Object) {
green = red.green;
blue = red.blue;
red = red.red;
}
let redHex = red.toString(16);
let greenHex = green.toString(16);
let blueHex = blue.toString(16);
if (redHex.length == 1) redHex = "0" + redHex;
if (greenHex.length == 1) greenHex = "0" + greenHex;
if (blueHex.length == 1) blueHex = "0" + blueHex;
return "#" + redHex + greenHex + blueHex;
}
rgbToHex({ red: 120, green: 50, blue: 5 }) // "#783205"
rgbToHex(120, 50, 5) // "#783205"
I am seeking advice on how to configure the function signatures so that it works seamlessly without any casting or unnecessary variable setups within the function body. I want to avoid something like
let gVal: number = g || (r as any).g;
.
Another option could involve splitting this into two functions and having one call the other, but applying such a solution with TypeScript seems inappropriate when compared to JavaScript.
Apologies if this has been asked before. I've searched extensively but couldn't find a solution addressing this specific issue.