Search code examples
typescriptcompile-time

Pass compile-time type parameter to implementation at runtime?


I'm trying to write an API that validates the runtime type of typescript variables. I'd like to record what type of variable the user is expecting at compile-time and validate it at runtime; unfortunately, I have only figured out how to look up a variable's type at runtime.

Example:

interface Validator
{
  getType(): string;
};

class NumberValidator implements Validator
{
  public getType(): string
  {
    return "number";
  }
}

class BooleanValidator implements Validator
{
  public getType(): string
  {
    return "boolean";
  }
}

function getValidator(value: number | undefined | null): NumberValidator;
function getValidator(value: boolean | undefined | null): BooleanValidator;
function getValidator(value: number | boolean | undefined | null): NumberValidator | BooleanValidator
{
  if (typeof(value) === "number")
    return new NumberValidator();
  return new BooleanValidator();
}

const numberValidator: NumberValidator = getValidator(123);
const booleanValidator: BooleanValidator = getValidator(false);
const incorrectValidator: BooleanValidator = getValidator(123 as unknown as boolean);

console.log("numberValidator: " + numberValidator.getType());
console.log("booleanValidator: " + booleanValidator.getType());
console.log("incorrectValidator: " + incorrectValidator.getType());

In the above code, I'd like incorrectValidator to be of type BooleanValidator. Is there a way to capture this information at compile-time without forcing the user to pass this information manually?

By "pass this information manually" I mean, I'd like to avoid declaring different function names depending on the expected type. Nor do I want the user to explicitly tell me the type of the value they are passing in. I want Typescript to infer the compile-time type, and access it from within the function at runtime.

What are my options?


Solution

  • It is impossible for getValidator(123 as unknown as boolean) to behave differently at runtime from getValidator(123). TypeScript's type system is completely erased upon compilation to JavaScript. That means both of the above expressions are compiled to getValidator(123). Any trace of boolean has been removed by the time JavaScript runs, so there's nothing left at runtime to distinguish those calls. Type erasure is fundamental to the design of TypeScript. It is explicitly not a design goal (see #5) to allow the results of the type system to affect runtime behavior. TypeScript types are not reified; you can't use reflection to access them.

    So, if you want two expressions to have different behavior at runtime, you need to make sure these expressions differ at the value level, not just at the type level. That implies you'd want to write something like getValidator("number") and getValidator("boolean") where you're encoding your intent in string literal values. TypeScript gives string literal types to these values, so you could make the above strongly typed in TypeScript so it realizes that getValidator("number") returns NumberValidator and getValidator("boolean") returns BooleanValidator, and depending how fancy you want to get, you could have TypeScript compute this type mapping for you:

    class NumberValidator implements Validator {
      public getType() {
        return "number" as const; // literal "number" return type
      }
    }
    
    class BooleanValidator implements Validator {
      public getType() {
        return "boolean" as const; // literal "boolean" return type
      }
    }
    
    type Validators = NumberValidator | BooleanValidator;
    
    type ValidatorMap = { [T in Validators as ReturnType<T["getType"]>]: T }
    /* type ValidatorMap = {
        number: NumberValidator;
        boolean: BooleanValidator;
    } */
    
    const validatorMap: { [K in keyof ValidatorMap]: new () => ValidatorMap[K] } = {
      number: NumberValidator,
      boolean: BooleanValidator
    }
    
    function getValidator<K extends keyof ValidatorMap>(value: K) {
      return new validatorMap[value];
    }
    
    const numberValidator: NumberValidator = getValidator("number");
    const booleanValidator: BooleanValidator = getValidator("boolean");
    

    But this is using value-level code to distinguish things at the type level, which is the reverse of what you're trying to do. Maybe you can make that work for your use case. If not, then you'll either need to give up or change your build process with a transformer or plugin that reifies types in some way. But such transformers are no longer pure TypeScript and you'd need to find or build one, which is beyond the scope of this answer.

    Playground link to code