简体   繁体   中英

Type 'X' cannot be used as an index type

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 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" string | "literal" the more general type subsumes the more specific constituents of the union.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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