Imagine you have an object like this:
const exampleObject = {
key1: {id: 1},
key2: {id: 1},
key3: {id: 1},
key4: {id: 1},
....
}
and a function that transforms the object to:
const transformedObject = {
key1: 1,
key2: 1,
key3: 1,
key4: 1,
....
}
using a function like this:
function transformObject<MyInputInterface>(input: MyInputInterface): MyOutputInterface? {
const newObject = {};
_.forIn(input, (value, key) => {
newObject[key] = value.id;
}
return newObject;
}
Is there a method in Typescript where you can define just one interface that automatically captures the structure of the other interface (either input or output)?
For instance, passing MyInputInterface
into the function will yield MyOutputInterface
?
This kind of scenario frequently arises in my codebase where a library extracts metadata and only provides specific values (e.g. id). I could create separate interfaces for input/output to gain more type information, but I'm curious to know if there's a way to define either input OR output and derive the other type information implicitly.
To illustrate this concept better, consider the following example:
const data = {
propA: {
desc: 'property a',
val: 1
},
propB: {
desc: 'property b',
val: 'hello'
}
// any number of properties
};
needs to be converted to:
const processedData = {
propA: 1,
probB: 'hello'
};