Stringly Typed
- Published at
- Updated at
- Reading time
- 2min
I learned a new software development term from Scott Hanselman: "stringly typed".
Scott describes "stringly typed" as follows:
[whenever] you are passing strings around when a better type exists.
An application is "stringly typed" when type information is available, yet you're calling other systems or functions based on strings or stringified data. Unsurprisingly, most API calls are "stringly typed" because request and response bodies are often stringified JSON data.
const response = await fetch("https://example.org/subscribe", {
method: "POST",
body: JSON.stringify({ username: "...", password: "..." }),
});
const user = await response.json();
JavaScript is a weakly typed language without much type safety, so the type loss wasn't a big deal for me so far. And because most APIs speak JSON, the possible types are limited to strings, numbers, objects, arrays, booleans and null
anyway.
We've all gotten used to this state of affairs, haven't we?
Let's flip things around for a moment:
- what if we considered API endpoints to be remote function calls?
- what if we considered API endpoints to be part of the frontend applications instead of remote interfaces?
The API call above could be seen as a subscribe
function with a username
and password
parameter that returns a user
object.
If you're using a strongly typed language like TypeScript, receiving the user
object as any
or unknown
type is unfortunate. You'll lose all the type safety and you can only regain it with manual type checking. "Stringly typed" types in a type-safe environment suck.
After building all these SPAs connecting to APIs being maintained by different teams, I've never considered it to be a huge problem, but now that I have a name for this pattern, "stringly typed" interfaces started to bother me.
I realize that I want type safety over the network and I don't want to deal with "stringly typed" apps at all. I want all the types!
Of course, the problem of "stringly typed applications" isn't new and there are JS solutions like tRPC or typed API interfaces like GraphQL out there. I played with GraphQL quite a bit but will explore type safety over the wire now.
However, I wonder if I had just had a TypeScript epiphany and will start to discover (and curse) "stringly typed" interfaces everywhere, just because I now have a name for it.
Join 5.8k readers and learn something new every week with Web Weekly.