3 ms·
To me - A type guard lets me be as picky as I'd like to be in the given circumstance. I also use axios, and I also take advantage of the generics you've shown
by horsawlarway 6y ago
To me - A type guard lets me be as picky as I'd like to be in the given circumstance.
I also use axios, and I also take advantage of the generics you've shown above, but I acknowledge that I'm essentially just saying "Trust me" and doing a cast when I do that.
And I'll add - that exact style of code has been a source of bugs in our production codebase before. A dev will pick the wrong type for the axios generic, and if the api response happens to overlap on the used fields, no one notices. Then it blows up 6 months later when someone tries to access a field on the defined type that wasn't actually returned in the api response.
- lhorie 6y ago> And I'll add - that exact style of code has been a source of bugs in our production codebase before. Very much this. That scenario will break if e.g. the backend API changes. This is a constant source of frustration for someone I know, whose backend team has a habit of not communicating their changes to the frontend team. There's nothing TS can do to enforce that the actual type of the response matches what the type declaration says (hence the need for runtime checks in this case).
- seer 6y agoIf the api has some contract with it OpenApi / Swagger / etc, its surprisingly easy to write a parser that would convert those to typescript types. TS has an awesome use as a library itself where you can write the ast with, and then tell it to convert it to code. We use it to great effect ourselves, by generating types for axios. https://github.com/ovotech/laminar/tree/main/packages/laminar-cli#axios-type-generation https://github.com/ovotech/laminar/tree/main/packages/lamina... Now granted, you’re now trusting the api writers with their contract, but if its another team in the org we’ve found it to be warranted.