Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
TypeScript 4.3 Beta (devblogs.microsoft.com/typescript)
40 points by flipchart on April 6, 2021 | hide | past | favorite | 4 comments


Template string types are neat, and I'm excited to see what new functionality is afforded. I've already been able to use them for probably ill-advised magic (... not in production anywhere), like this type for "strings with no leading or trailing spaces":

    type RSTRIP<STR> = STR extends `${infer T} ` ? RSTRIP<T> : STR;
    type LSTRIP<STR> = STR extends ` ${infer T}` ? LSTRIP<T> : STR;
    type STRIP<STR> = RSTRIP<LSTRIP<STR>>;
which allows things like:

    function strip<T extends string>(str: T): STRIP<T> {
        return str.trim() as STRIP<T>;
    }
    function printStripped<T>(str: STRIP<T>) {
        console.log(str);
    }
    printStripped('hi');
    //X printStripped(' hi');
    printStripped(strip(' hi'));


It’s odd to me that the Promise check is under the `strictNullChecks` flag. A Promise will never be `null` with that flag enabled.


In the case they showed, it’s correct though. A promise will never be null, but it’s resolved value might be (or it might reject). I’m actually surprised this took so long to get into the language, it seems like an “easy” mistake to make by, for example, forgetting to add an “await” and then not adding a test for the rejection of that promise.


This explanation makes sense of how they arrived at this, but it still doesn’t make sense to me under the flag. It’s type checking:

1. Something that can never be null

2. Based on code that’s not present

3. Which even if it were present wouldn’t necessarily be subject to strictNullChecks (even the example they used wouldn’t!)

Having had some more time to think about it, not only do I think it’s odd, I think it should change (and my next stop is their GH issues to say so/upvote whoever already has). It violates the principle of least surprise, which is very much at odds with the language’s mission.

Note that I’m not necessarily advocating for yet another flag/compilerOptions entry. I’d much rather they roll everything up in `strict`, and I’d even more rather they remove the non-strict option altogether for .ts files.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: