top | item 28838921

(no title)

mithusingh32 | 4 years ago

Wow, thanks for this. I wasn't even aware of these.

I'm surprised I rarely see these in courses/tutorial. These should be like day 1 material.

discuss

order

skywal_l|4 years ago

Typescript is actually a great language. And with those utility types, you can do pretty fun stuff like, for example, you want to mutate a type so that some fields become mandatory:

    type Ensure<T, K extends keyof T> = T & { [U in keyof Pick<T, K>]-?: T[U] };

    class A {
      foo?: number;
      bar?: number;
      baz?: number;
    }

    type MandatoryFields = "foo" | "baz";

    type B = Ensure<A, MandatoryFields>;

    const b: B = { foo: 42 };
Here, ts will complain that b is missing baz.

CuriouslyC|4 years ago

Why write code like that, instead of extending the class with a mandatory property? The above code is going to be inscrutable to a lot of engineers, and this isn't something like an ORM where there's a good reason for that.

yulaow|4 years ago

This seems extremely hard to read for me, I would have an hard time trying to understand what it does if I found it in any source code

flippinburgers|4 years ago

Just have a concrete type (class/interface) that specifies required fields.

This is overkill that will only confuse everyone who isn't the original author.

dllthomas|4 years ago

I don't have it handy but with template literal types I was able to have a type of "stripped strings" (that is, strings without leading or trailing whitespace) that seemed surprisingly usable - string literals would match (or not, as appropriate) with no boilerplate, while dynamic strings would need to be fed to a cleaning function.

I never put it in production, partially because of concerns over maintainability but far more because I had no need for it.

ketzo|4 years ago

Ok, the comments that this is a little hard to read are fair... but this is really cool. Thanks for sharing.

goto11|4 years ago

Depends on how much you can learn on one day I guess, but TypeScript have lots of features which should be learned before Utility types. For example type parameters, type unions, the role of null and undefined, type assertions etc.

shadowgovt|4 years ago

TS has been around long enough that it suffers from the 'obsolete tutorial' problem (one I first observed learning C++): many of the utility types didn't exist when many of the popular tutorials were first written.