0

supposing I have to read some data from some json files(i18n), every json file may look like:

{
  "foo": "1",
  "bar": "2",
  ...
}

I don't know how many fields this json have(it can be expanded), but it's fields look like

{
 [prop: string]: string
}

besides, all the json files share the same fields. when I try to read a value from this json via:

//a can be expanded, I'm not sure how many fileds does it have
let a = {
    name: "dd",
    addr: "ee",
}

//I'm confident a has a field "name"
let b = "name";

console.log(a[b]);

the error message is:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

how could I fix it?

1
  • I just tested. No any error message. Everything is working properly. Commented Nov 30, 2021 at 23:59

1 Answer 1

1

The error you're encountering is because the keys in a is not just any string (in fact, it can only be "name" or "add"), but b can be a string of any arbitrary value. If you are very sure that b represents a key found in the object a, you can hint TypeScript as such:

let b: keyof typeof a = "name";

Attempting to assign any arbitrary string value to b will lead to an error:

// This will cause an error
let b: key typeof a = "foobar";

See proof-of-concept on TypeScript Playground.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.