Comment

Comment by skywal_l

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.
parent skywal_l 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton