1

I am trying to check if a given string value is a valid value at some string union type in typescript. Something like this:

export default class TypeGuard<U extends string> {
  isSafe<T extends string>(candidate?: T): ((T & U) | undefined) {
    if (!candidate) return undefined;
    let result: T & U;
    try {
      result = candidate as T & U;
    } catch (error) { // expect TypeError
      return undefined;
    }
    if (!result) return undefined;
    return result;
  }
}

But the as operator don't works as I desired. Searching over the internet I found various "solutions" that basically creates an array with all valid values, uses this array to define the union type, and checks if the array includes the desired value. But this is not a valid solution to my case, because I don't define the union type, it is defined in an external library. Anyone knows another alternative to perform this check?

1 Answer 1

2

Remember that in Typescript, all type information is erased at runtime. The as operator doesn't do anything at runtime, and won't throw a type error.

Therefore, the only way to check at runtime if a value is in the union is to create an array, as you said. Since you don't define the union type yourself, I don't see a way to have the array automatically created - you'd have to manually create it based on the union values.

Another option would be to only do the check at compile time, however I imagine you have particular reasons for only wanting to do the check at runtime.

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

1 Comment

Yes, the reason is that I have a file with some config values, that file basically get values from .env, format this value and attribute default values for the missing or wrong informed ones. So I want to use this to prevent some mistake at the .env. It is not a critical issue, but wold be a desired improvement in starting application process security. Thanks.

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.