admin管理员组

文章数量:1287484

I receive en error in typescript:

message: 'Type 'TransitionStyles' cannot be used as an index type.'

I would like to know if it is possible to change my interface so it can also be used and an index type:

export interface TransitionStyles {
  entering: Object
  entered: Object
  exiting: Object
  exited: Object
  [key: string]: Object
}

or I am forced to use a different interface as:

export type TransitionState = 'entering' | 'entered' | 'exiting' | 'exited'

I receive en error in typescript:

message: 'Type 'TransitionStyles' cannot be used as an index type.'

I would like to know if it is possible to change my interface so it can also be used and an index type:

export interface TransitionStyles {
  entering: Object
  entered: Object
  exiting: Object
  exited: Object
  [key: string]: Object
}

or I am forced to use a different interface as:

export type TransitionState = 'entering' | 'entered' | 'exiting' | 'exited'

Share Improve this question asked Nov 23, 2017 at 13:15 GibboKGibboK 74k147 gold badges451 silver badges674 bronze badges 4
  • Use keyof. Also, don't use the Object type. Use object or {}, depending on which you mean. – Aluan Haddad Commented Nov 23, 2017 at 13:18
  • I have tries [key: TransitionState ] but does not work, could you please provide me with an example – GibboK Commented Nov 23, 2017 at 13:30
  • You have to use type T = {[P in TransitionState]}. It does not currently work for interfaces. – Aluan Haddad Commented Nov 23, 2017 at 13:48
  • Could you write a full example? – GibboK Commented Nov 24, 2017 at 7:33
Add a ment  | 

1 Answer 1

Reset to default 10

I think you want something akin to

export interface TransitionStyles {
  entering: object;
  entered: object;
  exiting: object;
  exited: object;
}

export type TransitionState = keyof TransitionStyles;

export type PromisifiedTransitionStyles = {
  [P in TransitionState]: Promise<TransitionStyles[P]>
};

Note that if we reintroduce the string index signature, [key: string]: TransitionState, the key type TransitionState, will collapse to just string because in the type string | "literal" the more general type subsumes the more specific constituents of the union.

本文标签: javascriptType 39X39 cannot be used as an index typeStack Overflow