0

How to define type of an object whose properties are going to be fetched from an array in TypeScript.

In the following example, how can I define the type of lookUpMap object?

const arr1 = ["a", "b", "c", "d"];
const arr2 = ["x", "y", "b"];

class Arr {
    
    private lookUpMap = {}
    
    constructor(private arr1: string[], private arr2: string[]){}    
    
    linearCompare(){
        for(let i of this.arr1){
            this.lookUpMap[i] = true
        }
        
        for(let i of this.arr2){
            if(this.lookUpMap[i]){
                return console.log(true);
            }
        }
        return console.log(false);
    }
}

const arrComp = new Arr(arr1, arr2);
arrComp.linearCompare()

Thank you

1 Answer 1

1

The most straightforward type I can think of for lookupMap is a dictionary-like object with a string index signature whose properties are of type true | undefined:

  private lookUpMap: { [k: string]: true | undefined } = {}

This will let you write true to any string-valued key, as in this.lookUpMap[i] = true, and understand that when you read from a string-valued key, the result will either be true or undefined, as in if (this.lookupMap[i]) {...}.

Note that this has nothing to do with the fact that your keys are coming from arrays; lookupMap will allow you to index into it with any string whatsoever.

Playground link to code

2
  • wondering if something like this would be possible: const arr1 = ["a", "b", "c", "d"] as const; type ArrKey = {[key in typeof arr1[number]]: true};
    – Nishant
    Feb 12, 2021 at 2:52
  • 1
    You can try that but since arr1 is outside the class and then passed into properties of the class, you'd need the class to be generic to keep track of this... and then looking up an element of arr2 will be annoying since it won't be known to be a key of lookupMap.
    – jcalz
    Feb 12, 2021 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.