I want to create a parse<Type>() function that parses a string and returns an object, but I want parse() to return the correct type, and I am struggling.
type Identity = {
name: string;
};
type ContactDetails = {
phone: string;
email: string;
};
function parse<T extends Record<string, string>>(input: string): T {
const result = {};
input.split('&').forEach(bits => {
const [name, value] = bits.split('=');
result[name] = value;
});
return result;
}
parse<Identity>('name=Paulin');
parse<ContactDetails>('phone=0123456789&email=paulin@email.com');
I get a TypeScript error:
Type '{}' is not assignable to type 'T'. '{}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record'.ts(2322)
I understand what the problem is: {} is not compatible with a generic Record type. But how can I solve this?
Thank you very much!