In my TypeScript project, I am currently working on a function to clone a specific block or page in Notion through the API. Although there is no direct endpoint available for duplicating pages programmatically, I have taken it upon myself to try and create a solution (despite being aware that there may be more efficient methods already existing).
So far, I have managed to recursively go through all the nested children of the designated page. However, I have encountered some challenges when it comes to generating the duplicated blocks themselves. The BlockObjectResponse
type provided by Notion, which encompasses around 30 other response types in a union format, has posed difficulties. These types share common properties like type, id, parent (which is another complex union type), etc., which are essential for reconstructing relationships during the creation of the copy. While discarding irrelevant properties like edit times and users, the variation among these fields has made it hard to streamline my code. Consequently, I have resorted to using a cumbersome switch statement-based parsing method that I believe could probably be improved.
https://i.sstatic.net/V0b0n1Ot.png.
To address this issue, I have employed workarounds such as converting the type values of all child objects into strings and iterating over them. This involves utilizing unconventional JSON serialization and deserialization techniques to bypass potential TypeScript errors. Is there a more standardized approach to refine these types and eliminate the need for such workarounds?