skip to Main Content

I’m getting the following error when trying to use a dynamic value for an array key.

Element implicitly has an 'any' type because expression of type '`faults_${string}`' can't be used to index type 'HeatsTable'.
export interface HeatsTable {
    heat_id: UUID
    start: number
    faults_1: string[]
    faults_2: string[]
    faults_3: string[]
    faults_4: string[]
  }

const fault = heatData[`faults_${runningId}`]; // Throws the above TS error

Using keyof HeatsTable works but causes an error on another page because it thinks faults could be a number. Is there another solution for this that I’m missing?

2

Answers


  1. what if using this answer ?

    const fault = heatData[`faults_${runningId}` as keyof HeatsTable];
    
    Login or Signup to reply.
  2. You could type runningId either manually or with extracting it from the type:

    Playground

    export interface HeatsTable {
        heat_id: string
        start: number
        faults_1: string[]
        faults_2: string[]
        faults_3: string[]
        faults_4: string[]
      }
    
    declare const heatData: HeatsTable;
    declare const runningId: number;
    
    type RunningId = keyof {[K in keyof HeatsTable as K extends `faults_${infer A extends number}` ? A : never]: any}
    
    const fault = heatData[`faults_${runningId as 1|2|3|4}`];
    const fault2 = heatData[`faults_${runningId as RunningId }`];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search