generic function that parses object from string and returns object as matching interface. in typescript

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.ts
interface MyInterface {
  name: string;
  age: number;
}

function parseStringToObject<T extends object>(str: string): T {
  try {
    const obj: T = JSON.parse(str);
    return obj;
  } catch (err) {
    throw new Error(`Error parsing string '${str}' to object: ${err.message}`);
  }
}

const myObjString = '{"name":"John Smith","age":30}';
const myObj: MyInterface = parseStringToObject<MyInterface>(myObjString);

console.log(myObj); // { name: 'John Smith', age: 30 }
472 chars
19 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