1

I am trying to add some types to some old code.

There is a transitionData object, that might have objects added by index like this:

this.transitionData[id] = transition

where id is a number and transition is a Transition type.

Or it might be:

transitions[t].timer.stop()

Where t is a string and timer is of type Timer.

I would like this interface:

export interface TransitionData {
  [index: number]: Transition
  [key: string]: {timer: Timer}
}

but typescript complains:

Numeric index type 'Transition' is not assignable to string index type '{ timer: Timer; }

1 Answer 1

1

Create two index signatures and merge them together.

interface TransitionMap {
    [index: number]: Transition
}

interface TimerMap {
    [index: string]: { timer: Timer }
}

declare const transitionData: TransitionMap & TimerMap;

TypeScript will understand what goes where.

transitionData["1"] // Timer
transitionData[1]   // Transition
Sign up to request clarification or add additional context in comments.

1 Comment

The reason TS is not happy about this is that the way indexing works in JS, transitionData["1"] === transitionData[1] (ex: typescript-play.js.org/#code/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.