I once read a very good book on writing "bug-free C". It is old, it was already dated when I found it, but I keep remembering the foundational approach. Say, you got a bug; what to do? Fix it, of course. But then think: how to make sure you won't make the same mistake next time? And it has to be a technical solution, not a feat of will or attention.
Types are an attempt to prevent certain bugs from reappering. They are not perfect, of course. The general problem is that we do not know how to design programs yet.