简体   繁体   中英

Iterate over object in Typescript to find propety and its value

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 ?

const validKeys: Array<Extract<keyof Book, string>> = [
  "lcc",
  "lccn",
  "isbn",
  "olid",
];
const validKey = validKeys.find((x) => x in book);
const validKeyValue = validKey && book[validKey];

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