A
A
Alex2021-11-25 19:25:38
typescript
Alex, 2021-11-25 19:25:38

How to write a function that returns a class depending on the parameter?

There is a set of classes.

class TimeoutTextValidator {
  public static type = 'timeout-text' as const
  public schema = {timeout: 1}
}

 class ImageValidator {
  public static type = 'image' as const
  public schema = {src: ''}
}


All have a static unique field type.

I want to write a function that would return the desired class by the passed type:
export function getValidatorByType(type) {
  switch (type) {
    case 'timeout-text':
      return TimeoutTextValidator
    case 'image':
      return ImageValidator
    default:
      return assertUnreachable(type)
  }
}

function assertUnreachable(_: never): never {
  throw new Error("Didn't expect to get here");
}


The problem is types. I can't figure out how to make the TS correctly infer the return type depending on the passed argument.

My attempts at the playground

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-11-26
@Kozack

I would do this:
https://www.typescriptlang.org/play?#code/PTAEiQQR...

I
Igor Makhov, 2021-11-25
@Igorgro

This is what you need: https://www.typescriptlang.org/play?#code/MYGwhgzh... ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question