简体   繁体   English

typescript是否允许接口和字符串联合类型?

[英]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 . 我正在尝试实现一个方法,它采用一个键参数,该键参数是string或可索引类型接口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: Typescript为if块提供以下错误:

[ts] 'IValidationContextIndex' only refers to a type, but is being used as a value here. [ts]'IValidationContextIndex'仅引用一个类型,但在此处用作值。

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 .... 对于大多数接口,我认为可以添加一个type属性( type: 'IValidationContextsIndex' ;),但在这种情况下不起作用,因为接口是一个可索引类型的接口....

有一种方法可以在运行时检查typescript中的类型,因为几乎所有内容都会在转换后成为一个对象,所以你可能需要做一些定义为用户定义的类型保护的东西

I think this will do it (Per the tip from @indrakumara): 我认为这样做(根据@indrakumara的提示):

    /**
     * Gets all ValidationContext container values fpr a 
     * Object_property string valued key or a key that is an instance of 
     * IValidationContextIndex).
     * @returns An array of ValidationContext instances contained in the cache that corresponds to a specific Object_property key.
     */
    public static getValidationContextValues(key: any ): Array<ValidationContext> {
      if (typeof key === `string` ) {
        const vci = ValidationContainer.cache[<string>key];
        return Object.values(<any> vci);
      }
      else {
        return Object.values(<IValidationContextIndex> key);
      }
    }  

Interfaces in typescript doesn't transpile into any code in javascript. 打字稿中的接口不会转换为javascript中的任何代码。 So in your code, "instanceof IValidationContextIndex", IValidationContextIndex doesn't exist in javascript. 因此,在您的代码中,“instanceof IValidationContextIndex”,IValidationContextIndex在javascript中不存在。

Change your interface to class or have a class implementing the interface and then check if passed parameter is instanceof that class. 将您的接口更改为类或具有实现该接口的类,然后检查传递的参数是否是该类的instanceof。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM