rimeto / ts-optchain

Optional Chaining for TypeScript
MIT License
577 stars 17 forks source link

Problem with union types (reopened) #15

Open abcdev opened 5 years ago

abcdev commented 5 years ago

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 commented 5 years ago

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 (https://github.com/Microsoft/TypeScript/issues/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 commented 5 years ago

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.