Skip to content
This repository has been archived by the owner on Feb 26, 2021. It is now read-only.

Problem with union types (reopened) #15

Open
abcdev opened this issue Jan 28, 2019 · 2 comments
Open

Problem with union types (reopened) #15

abcdev opened this issue Jan 28, 2019 · 2 comments

Comments

@abcdev
Copy link

abcdev commented Jan 28, 2019

The issue of #10 stays and 'just switch to intersection instead of union' is not a solution. The same is valid for 'just assign it to any' as pointed out in #12 .

Issue illustrated in #10 or at https://stackblitz.com/edit/ts-optchain-any-g9clab?file=index.ts

@threehams
Copy link

threehams commented Apr 7, 2019

I'm not sure if this is possible at all in TypeScript at the moment.

interface WithString {
  a: string;
}

interface WithFunction {
  a?: {
    func: (event: any) => void;
  };
  b: number[];
}

const doStuff = (data: WithString | WithFunction) => {
  oc(data).a. // ???
}

The parameter passed into data would have to be dynamically converted to an intersection of all union types. This conversion is already sketchy by itself (microsoft/TypeScript#29594). I'm not even sure if it's possible to dynamically narrow a union based on dynamic parameters within a library - after all, it would have already been done for Array.prototype.filter.

Edit:
I think I might have this working? Needs a lot more testing.

@hdennen
Copy link

hdennen commented Apr 12, 2019

My first though would be type assertion as per my comment in #10, but that seems to come with it's own weirdness when I tried your StackBlitz.

The other option is generics: https://stackblitz.com/edit/ts-optchain-any-5bdcmf?file=index.ts which we use pretty extensively since any and intersection are not really good options.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants