class Lol {
    get length() {
        console.log('Lol. LMAO even.');
        return 5;
    }
}

const noLolsAllowed = (notALol: string) => {
    for (let i = 0; i < notALol.length; ++i) {
        console.log('No lols here');
    }
}

noLolsAllowed(new Lol() as unknown as string);
  • as is an escape hatch and super dangerous. I think they shouldn’t have given it such a nice name. unsafeCastAs would have been much better IMHO.

    It does require the uglier as unknown as in cases where it can provide that the cast is impossible. But that still allows many cases such as Foo|undefined as Bar|undefined working fine (TypeScript assumes undefined and doesn’t require the cast via unknown).