简体   繁体   中英

typescript and reactjs : how to use map - ERROR ts(7053)

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)

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])

const array1:String is not specific enough (and even if you had to do something like that, use string , not String ). Specify that array1 contains keys of the object (which should probably be called something like myTypeObj - it's an object, not an array):

type MyType = {
    prop1: string,
    prop2: string
}
const myTypeObj: MyType = { prop1: "value1", prop2: "value2" };
const array1: Array<keyof MyType> = ["prop1", "prop2"];

console.log(array1.map(x => myTypeObj[x])

Another option is to just keep TS from automatically widening the array1 items to string :

const array1 = ["prop1", "prop2"] as const;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM