Home > front end >  Typescript doing unasked for intersection
Typescript doing unasked for intersection

Time:10-12

I have this setup

type MyType = { reason: string };
type OnAccept = (arg0: string) => void;
type OnReject = (arg0: MyType) => void;

const cbAction = (cb: OnAccept | OnReject) => (params: string | MyType) => {
  cb(params);
  // do stuff
};

but Typescript is complaining with Argument of type 'string | MyType' is not assignable to parameter of type 'string & MyType'


I tried this but it didn't work as well
const cbAction = <T extends OnAccept | OnReject>(cb: T) => (params: T extends OnAccept ? string : MyType) => {
  cb(params);
  // do stuff
};

How to implement this without the compiler complaining?

Where did the intersection string & MyType come from?

CodePudding user response:

You define cbAction to be a function that gets a parameter cb which can be of type OnAccept or OnResult. In your function you execute this callback cb(params). Since we don't know if cb is OnAccept or OnResult, params must satisfy both: i.e. string & MyType

enter image description here

I guess this is what you want to do:

const cbAction = <T extends string | MyType>(cb: (arg0: T) => void) => (params: T) => {
  cb(params);
  // do stuff
};

cbAction((arg0: string) => arg0)("abc");
cbAction((arg0: MyType) => arg0)({
    reason: 'abc'
});
  • Related