Blog · GitLab (User) Created at 2018-4-21 09:42:26 Updated at 2018-4-28 10:45:27 Tomáš Hübelbauer
Document how to enable importing images in TypeScript

TypeScript

Discriminated class union

My example on GitHub

Interesting Thingy #1

I was wondering is something like this was possible in TS:

type Test =
    | { type: 'a'; a: boolean; }
    | { type: 'b'; b: number;}
    | { type: 'c'; c: string; d: string; }
    ;
test<t extends Test>() {
    // The switch should understand it is switching on `'a' | 'b' | 'c'` now
    // The switch should infer T to be the respective type union variant in the `case` branch
    // `as T` in the `case`s is for clarity also (it should be infered as per the above point)
    switch (foo(T).type) {
        case 'a': return barA() as T; // T is { type: 'a', a: boolean; }
        case 'b': return barB() as T; // T is { type: 'b', b: number; }
        case 'c': return barC() as T; // T is { type: 'c', c: string; d: string; }
        default: throw new Error(); // T is `never`
    }
}

I wasn't sure what foo would be here, not typeof.

But then I realized, if it's impossible in JavaScript, it's going to be impossible in TypeScript. And we are not passing any type information in the actual runtime, consider this:

test() {
    switch (foo(T).type) {

    }
}

There is no place the T could come from, in JS, it's all but forgotten. If we did pass an instance of T as a parameter, then it could work, but that didn't suit my design, so I made a different choice in the end.

Importing images

  1. index.d.ts: declare module '*.png';
  2. index.tsx: /// <reference path='./index.d.ts'/>
  3. index.tsx: import checkerboard from './img/checkerboard.png';
Changes (3)
2018-4-28 10:45:27 Tomáš Hübelbauer
Document how to enable importing images in TypeScript
2018-4-23 18:52:13 Tomáš Hübelbauer
Bookmark my discriminated class union demo
2018-4-21 09:46:23 Tomáš Hübelbauer
Note down the interesting case I ran into
Comments E-mail me!