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);
  • kevincox
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    2 years ago

    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 prove 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).