Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Discriminated Union Type with default and type inference

I want to create a Discriminated Union Type, where it isn't required to pass the discriminator value.

Here's my current code:

interface Single<T> {
  multiple?: false // this is optional, because it should be the default
  value: T
  onValueChange: (value: T) => void
}

interface Multi<T> {
  multiple: true
  value: T[]
  onValueChange: (value: T[]) => void
}

type Union<T> = Single<T> | Multi<T>

For testing I use this:

function typeIt<T>(data: Union<T>): Union<T> {
    return data;
}

const a = typeIt({ // should be Single<string>
    value: "foo",
    onValueChange: (value) => undefined // why value is of type any?
})

const b = typeIt({ // should be Single<string>
    multiple: false,
    value: "foo",
    onValueChange: (value) => undefined
})

const c = typeIt({ // should be Multi<string>
    multiple: true,
    value: ["foo"],
    onValueChange: (value) => undefined
})

But I get a bunch of errors and warnings...:

  1. In const a's onValueChange the type of the parameter value is any. When setting multiple: false explicitly (like in const b) it gets correctly inferred as string.

  2. const c doesn't work at all. I get this error: "Type 'string' is not assignable to type 'string[]'".

Do you have any idea how to solve this?

I've created a TypeScript Playground with this code

like image 842
Benjamin M Avatar asked Jan 03 '19 22:01

Benjamin M


Video Answer


1 Answers

I don't think the compiler can easily infer the type of the value parameter in the callback since the type of the object literal is still not determined when the callback is checked.

If you don't have a lot of union members a solution that works as expected is to use multiple overloads:

export interface Single<T> {
  multiple?: false // this is optional, because it should be the default
  value: T
  onValueChange: (value: T) => void
}

interface Multi<T> {
  multiple: true
  value: T[]
  onValueChange: (value: T[]) => void
}

type Union<T> = Single<T> | Multi<T>

function typeIt<T>(data: Single<T>): Single<T>
function typeIt<T>(data: Multi<T>): Multi<T>
function typeIt<T>(data: Union<T>): Union<T> {
    return data;
}

const a = typeIt({ // is Single<string>
    value: "foo",
    onValueChange: (value) => undefined // value is typed as expected
})

const b = typeIt({ // is Single<string>
    multiple: false,
    value: "foo",
    onValueChange: (value) => undefined
})

const c = typeIt({ // is be Multi<string>
    multiple: true,
    value: ["foo"],
    onValueChange: (value) => undefined
})
like image 67
Titian Cernicova-Dragomir Avatar answered Oct 06 '22 02:10

Titian Cernicova-Dragomir