Hacker News new | ask | show | jobs
by paddy_m 356 days ago
I have a project that has a python backend and react typescript frontend. Both are typed. How do you all handle resolving types between two systems like that. Ideally I'd like to be able to write types in typescript, and write python types, then verify that the types are compatible (not identical). I frequently frontend side features that add new keys to dicts, and fill in python support later.
2 comments

> Ideally I'd like to be able to write types in typescript, and write python types, then verify that the types are compatible (not identical)

Have a look at https://fastapi.tiangolo.com/

FastAPI allows you to define your types in Python using Pydantic for stronger type guarantees. FastAPI also generates an OpenAPI.json file for your backend and then you can feed this OpenAPI.json document into https://github.com/OpenAPITools/openapi-generator to generate a typescript library that contains all the types. Then you don't need to verify your types, because the typescript types will be directly generated from your Python types. The generated typescript library also contains methods for each of your REST endpoints, so that you don't have to think about network requests.

So, this is a jupyter/anywidget project. I think OpenAPI can work, but it's a bit of grafting I think.

Further, I develop the frontend visualization library separately from the python code. It is much more natural to write typescript there, first for types that power the frontend. I just want to make sure earlier that python is sending the same types. I'd like to avoid pydantic, because it is a another dependency, and I control both sides. I'm not worried about an errant request/response, just proviing at build time that I am sending and receiving the proper compatible types.

Python type system is less expressive than TS, so defining types in Python and then generate (rather than write them manually) the equivalents in TS feels like the better way. There are tools to generate Typescript types/structures from OpenAPI definition for doing that.