简体   繁体   English

如何在typescript对象接口中键入字符串作为Object属性键?

[英]How to type a string as an Object property-key in a typescript Object interface?

I define an interface - the relevant part is here: 我定义了一个接口 - 相关部分在这里:

      actors:{    
        name:{           // options (Object) is specific to each actor type
                        // see documentation at top of each actor
          factory:string,
          url:string,
          options:Object
        }
        //...
      }

I implement the interface as follows: 我按如下方式实现接口:

      actors:{
        'unitcube':{ 
          factory:'Unitcube',
          url:'../src/app/models/stage/actors/objects/unitcube',
          options:{wireframe:false, 
                color:'red', 
                opacity:0.9, 
                transform:{t:[0.0,2.0,-3.0001],e:[0.0,1.0,0.0],s:[1.0,3.0,1.0]}
          } 
        }
        //...
      }//actors

The interface passes tslint, however I receive a tslint/tsc error that the types of the interface and the implementation are different - in particular 'unitcube' and name. 接口传递tslint,但我收到tslint / tsc错误,接口类型和实现方式不同 - 特别是'unitcube'和name。

How can I type-specify a list of string-named Objects? 如何键入 - 指定字符串命名的对象列表? (ie how do I define 'name' in the actors part of the interface?) (即如何在界面的actor部分中定义'name'?)

Thanks. 谢谢。

interface IActors {
   actors: IActorType
}

interface IActorType {
  [name: string]: //so on and so forth
}

the interface defined in the question enforces the key to be literally 'name.' 问题中定义的接口强制键实际上是“名称”。 when implemented with 'unitcube' or any other actor's name, it is evaluated to be not equal to 'name.' 当使用'unitcube'或任何其他actor的名称实现时,它被评估为不等于'name'。 [name: string] allows this key to be dynamic, so any actor name of type string can be used. [name:string]允许此键是动态的,因此可以使用任何类型为string的actor名称。

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

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