Reputation: 319
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
Upvotes: 0
Views: 150
Reputation: 330436
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.
Upvotes: 1