0

I have the following function:

enum EventType {
  First = 'first',
  Second = 'second',
}

type First = {
  first: string;
  type: EventType.First;
};
 
type Second = {
  second: string;
  type: EventType.Second;
};

type Data = First | Second;

interface Options<T extends EventType = EventType> {
  matcher: (data: Extract<Data, { type: T }>) => boolean;
  type: T;
}

function foo(options: Options) {
  ...
}

I'm trying to achieve strict types on the matcher functions data param based on the value of type. For example with this usage:

foo({
  matcher: data => ..., // data has type First
  type: EventType.First,
});

foo({
  matcher: data => ..., // data has type Second
  type: EventType.Second,
});

My code doesn't achieve this, I think because it isn't clear where the generic T takes it's value. Is it possible to do what I want?

1 Answer 1

1

foo must be made generic in order to allow Options to correctly infer the type:

enum EventType {
  First = 'first',
  Second = 'second',
}

type First = {
  first: string;
  type: EventType.First;
};
 
type Second = {
  second: string;
  type: EventType.Second;
};

type Data = First | Second;

interface Options<T extends EventType = EventType> {
  matcher: (data: Extract<Data, { type: T }>) => boolean;
  type: T;
}

function foo<E extends EventType>(options: Options<E>) {}

foo({
  matcher: data => true, // data has type First
  type: EventType.First,
});

foo({
  matcher: data => true, // data has type Second
  type: EventType.Second,
});

Playground

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.