1

我正在尝试迭代看起来像这样的对象:

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

这个想法是获取与数组中的名称匹配的任何属性,并返回此键及其值。这是我到目前为止得到的:

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;
    }
  }

这应该在普通的旧 Javascript 中工作,但在 Typescript 中我得到这个错误:

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'. 

有什么办法可以绕过这个吗?如何迭代 Typescript 中的对象属性?

4

1 回答 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];
于 2020-09-17T08:01:23.927 回答