Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does typescript allow interface and string union types?

I'm trying to implement a method like that takes a key argument that is either a string or an instance of the indexable type interface IValidationContextIndex. The implementation looks like this:

  /**
   * Gets all ValidationContext container values.
   * @returns An array of ValidationContext instances contained in the cache.
   */
  public static getValidationContextValues(key: IValidationContextIndex | string ): Array<ValidationContext> {
    if (key instanceof IValidationContextIndex ) [
      return Object.values(<any> key);
    ]
    else {
      const vci = ValidationContainer.cache[<string>key];
      return Object.values(<any> vci);
    }
  }  

Typescript give the following error for the if block:

[ts] 'IValidationContextIndex' only refers to a type, but is being used as a value here.

Any ideas on how to fix this?

For most interface I think it's possible to add a type property ( type: 'IValidationContextsIndex'; ), but that does not work in this case since the the interface is an indexable type interface ....

like image 204
Ole Avatar asked Aug 06 '26 21:08

Ole


1 Answers

There isnt a way to check the type in typescript at run time as almost everything becomes an object once transpiled, so you may have to something along what is defined as user-defined typed guards

like image 61
Jaya Avatar answered Aug 09 '26 12:08

Jaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!