Here is an example of how to create a generic function that parses a string and returns an object as a matching interface in TypeScript:
index.ts472 chars19 lines
In this example, we create an interface called MyInterface
that specifies the shape of the object we want to return. We then create a function called parseStringToObject
that accepts a generic type T
which extends object
. The function takes a str
parameter which is the string to be parsed to an object.
Inside the function, we try to parse the string into an object using JSON.parse
and assign it to an object of type T
. If the parsing is successful, we return the object. If not, we throw an error.
Finally, we create a string representation of an object that conforms to MyInterface
, and call the parseStringToObject
function with MyInterface
as the generic type parameter. Printing the contents of myObj
to the console confirms that we have successfully parsed the string into an object that matches the MyInterface
definition.
gistlibby LogSnag