UP | HOME

typescript

Table of Contents

25.5.20

1 .typescript

  1. tuples

    It is possible to use a sort of tuple like the following:

      const a = (): [string, string, number] => ['a', 3, 4];
    

    and typescript will complain about the `3` in there.

  2. tuples of particular length
    const hey = (n: [number, ...number[]] & {length: 3}) => console.log(n);
    hey([1, 2, 3, 4]) // this will complain very loud that it is too long
    
  3. data as types

    https://blog.logrocket.com/const-assertions-are-the-killer-new-typescript-feature-b73451f35802/ [[articles]]

    there is a way to distinguish minimum things as types nicely

    // import an object matching function that says { type: "person" } 'matches' { type: "person", and: "other data" }
    // similar to pattern matching
    import { matches } from "lodash/fp";
    // you can define a 'type const like this'
    const person = { type: "person" };
    // and typescript also allows you to
    const person = { type: "person" } as const;
    // then, you can construct a type out of this data
    type Person = typeof person & { any: "other fields" };
    // you can then use the type to assert types in functions
    const func = (p: Person): Person => doSomething(p);
    // but also use the const as data in other ways
    // such as asserting and checking arbitrary data
    const isPerson = (o: object): boolean => matches(person, o);
    
  4. exhaustive check in switch statement, check all cases covered

    in case you want to make sure all cases of a union type are abgedeckt, then you can do something as follows:

    interface Christmas { name: "Christmas" }
    interface Birthday { name: "Birthday" }
    interface Wedding { name: "Wedding" }
    
    type Event = Christmas | Birthday | Wedding
    
    const t: Event = data.event;
    
    switch (t.name) {
      case "Christmas": return "we wish you a merry christmas"
      case "Birthday": return "it's your birthday, you can cry if you want to"
      default:
        // this default ensures that if you add a new Event or forgot to check one,
        // the compiler will catch here that you must add a message
        ((x: `failed to handle this type`): never => {
          throw new Error(`${x} was unhandled in body creation`);
        })(t);
    }
    

    this should result in the error: error TS2345: Argument of type 'Wedding' is not assignable to parameter of type '"failed to handle this type"'.

    note, this only works when you switch on t.name and not set name to a const beforehand

Author: John Doe

Created: 2021-01-06 Wed 04:41