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 ?
stringtoauthor_namebut it expects astringarrayauthor_nameas 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.