1

I am trying to iterate over object that looks like this:

interface Book {
  title: string;
  author_name: string[];
  key: string;
  first_publish_year: number;
  first_sentence?: string;
  isbn?: string[];
  lcc?: string[];
  lccn?: string[];
  olid?: string[];
}

The idea is to get any property that matches the name in array and return this key with its value. Here is what I get so far:

const book : Book = {
  title: 'Some title',
  author_name: 'author',
  key: 'stuff';
  first_publish_year: 1994;
  first_sentence: 'stuff';
  isbn: [];
}

  let validKey = "";
  let validKeyValue = "";
  const validKeys = ['lcc', 'lccn', 'isbn', 'olid']
    
  for (let key of Object.keys(book)) {
    if(validKeys.includes(key)) {
     validKey = key
     validKeyValue = book[key]
      break;
    }
  }

This should work in plain old Javascript, but in Typescript I get this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Book'.
  No index signature with a parameter of type 'string' was found on type 'Book'. 

Is there any way that I can bypass this ? How can I iterate over object properties in Typescript ?

2
  • 1
    are you sure the error message included in your question in the only issue in your code? I see other problems like semi-colons instead of comma in the object literal and assignment of string to author_name but it expects a string array Commented Sep 17, 2020 at 7:47
  • 2
    You types and syntax is a mess. Are you sure that that error is the only error? Because you've typed author_name as an array of string, but you're assigning a single string to it. And you're using ; instead of , when you're constructing an object. Commented Sep 17, 2020 at 7:47

1 Answer 1

1
const validKeys: Array<Extract<keyof Book, string>> = [
  "lcc",
  "lccn",
  "isbn",
  "olid",
];
const validKey = validKeys.find((x) => x in book);
const validKeyValue = validKey && book[validKey];
Sign up to request clarification or add additional context in comments.

1 Comment

Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues.

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.