this is my first asked question in here, so please help me to improve.
In Typescript (ReactJs) given two arrays:
const array1:String = ["prop1", "prop2"];
const array2:MyType = { prop1 : "value1", prop2: "value2 }
where MyType is a kind:
type MyType = {
prop1: string,
prop2: string
}
how can i print “value1” with the following code?
console.log(array1.map(x => array2[x])
Right now I’am getting the following error:
const array2: MyType Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyType'. No index signature with a parameter of type 'string' was found on type 'MyType'.ts(7053)
Advertisement
Answer
You’re off to a good start, but there are a few things to fix!
Firstly, your first code snippet has incorrect types:
const array1:String = ["prop1", "prop2"];
const array2:MyType = { prop1 : "value1", prop2: "value2 }
array1 isn’t a String, it’s an array of strings. So its type should be string[]. You’re also missing a quote after "value2:
const array1: string[] = ["prop1", "prop2"];
const array2: MyType = { prop1: "value1", prop2: "value2" }
Next, you have a syntax error in your console.log—it’s missing the ending ):
console.log(array1.map(x => array2[x]))
Then lastly @CertainPerformance’s answer can come in and save you: the type of array1 can be made more specific.
const array1: (keyof MyType)[] = ["prop1", "prop2"]; // or, equivalently const array1: Array<keyof MyType> = ["prop1", "prop2"];
All together now:
type MyType = {
prop1: string,
prop2: string
}
const array1: (keyof MyType)[] = ["prop1", "prop2"];
const array2: MyType = { prop1 : "value1", prop2: "value2" }
console.log(array1.map(x => array2[x]))
Now, you asked about how to print value1. This will actually log ["value1", "value2"]. To log only the first one you can just access the first element after your .map():
console.log(array1.map(x => array2[x])[0])