Refactor into typescripted version