Throughout this year, I've been diving into the world of React and TypeScript. One thing that stood out to me is how challenging it can be to type complex objects. It got me thinking - wouldn't it be great if there was a way or a helper function that could take an object as input and return a TypeScript interface or type for us to use in our code?
For instance, consider the following object:
const complexObject = {
"hsl": {
"h": 118.48101265822783,
"s": 1,
"l": 0.5,
"a": 1
},
"hex": "#06ff00",
"rgb": {
"r": 6,
"g": 255,
"b": 0,
"a": 1
},
"hsv": {
"h": 118.48101265822783,
"s": 1,
"v": 1,
"a": 1
},
"oldHue": 118.48101265822784
}
Typing this object manually can indeed be quite daunting, especially for beginners like myself. But imagine if we had a library where we could simply call a function like getType
. We could then do something like this:
getType(complexObject);
// returns
type complexObject = {
hex: string;
hsl: { h: number; s: number; l: number; a: number };
hsv: { h: number; s: number; v: number; a: number };
rgb: { r: number; g: number; b: number; a: number };
};