so I've been working with react and typescript this year and I noticed how difficult it can sometime be to be able to type some complex objects. therefore, I was wondering if there could be a way or a helper function that we could call with an object and be able to return a typescript interface or a type back which we could then use to write it in our code and use it as a type for whenever we are using the object.
Example: say we have an object as such:
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
}
as you can see typing this object could be somewhat troublesome, especially to inexperienced developers like myself. now if there could be a library that we could call in this context getType
then we could do something like this:
getType(complexObject);
// return
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 };
};
CodePudding user response:
If you just want to use a type in a file the way you've written getType
above, use typeof
as in Ozan's answer. Though typeof
works at runtime to return a string in Javascript, TypeScript gives typeof
additional meaning: it allows you to reuse the type of an existing identifier.
// Runs in the emitted JavaScript.
const someValue = typeof complexObject; // "object"
// Type only: not emitted to JavaScript.
type someType = typeof complexObject; // { hsl: { ... }, ... }
// Type only as well, because it's after the : so TS reads it as a type.
const typedValue: typeof complexObject = getComplexObject();
// field name: type expression = initial value
Remember, types don't exist at runtime, so there isn't ever a chance that you could return a type as a runtime value or function return expression like getType
.
A function like getType
might return a value, and that value might have a useful type, but you can't return the type itself with a function.
Side note: if you're trying to write a declaration file based on existing Javascript code, or if you want to get to the interface definition so you can copy-paste it into your own code, a standard tool for that is dts-gen.
CodePudding user response:
You don't need a function like getType
to retrieve the type as a variable and reuse it in your code.
All you need to do is using the typeof
operator and assigning that value to a type
variable.
type ComplexObjectType = typeof complexObject;
Now, you can use ComplexObjectType
as a type to other variables in your project.