There are, of course, writers who do write what they know, and they are very successful and accomplished but they are definitely in the minority. James Harriet and Kathy Reich come to mind, along with detectives and lawyers who write true crime etc.
My book Amaranthine wouldn't exist if I followed this advice since I know next to nothing about: Denmark, London, 1885, owning a duck, being an orphan, killing someone, or being immortal. But I can use the internet and I dreamed up the rest. If it's not entirely historically accurate, that's ok.
I think the best advice for writers would be write what you love.