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?

5

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật