Consider this scenario:
There is a function called createObj
that takes an object as a parameter of type ExampleType
. It then creates a new object with a property def
which contains the provided object. The goal is for it to return a type that matches the type of the provided object. Here's an example:
type ExampleType = { aaa: string };
declare type MyFunc = <T>(obj?: ExampleType) => { def: O };
const myFunc: MyFunc;
const a = myFunc({aaa: 'name'});
Currently, it returns { def: any }
, but the desired output is { def: { aaa: 'name' } }
. Is there a way to achieve this? Alternatively, consider this simpler example:
const aObj = { a: true };
type aType = { a: true };
Is there a way to make the type of aObj
equal to aType
?
EDIT: I have found a partial solution to my question (based on this Create TypeSafe Object literal based upon existing object in TypeScript).
function myFunc<O>(keysAndValuesObj: O) {
return { def: keysAndValuesObj } as {
def: { [K in keyof typeof keysAndValuesObj]: K };
};
}
const a = myFunc({
aaa: 'abc'
});
// now variable a has a type of { def: { aaa: 'abc' } }
Now, the next step is to ensure that the argument of myFunc
is of type ExampleType
. I attempted to extend O
with the ExampleType
type, but without success...