Reputation: 529
I've been trying to extend my React capabilities, so trying to move a project over from Javascript to Typescript, but I'm getting some errors that I can't seem to fix.
I've done a lot of reading and searching, but can't seem to figure out what I'm doing wrong.
The other components work, as well as the main App. It's just this component.
// Imports
interface Props { }
interface State { }
class Anagram extends Component<Props, State> {
constructor(props: Props) {
super(props);
}
alphabetize(word: any) {
if (word) {
word = word.split('');
word = word.sort();
word = word.join('');
return word;
}
return;
}
getGroupedAnagrams(words: string[]) {
const anagrams = {};
words.forEach((word) => {
const sortedWord = this.alphabetize(word);
if (anagrams[sortedWord]) {
return anagrams[sortedWord].push(word);
}
anagrams[sortedWord] = [word];
});
return anagrams;
}
render() {
const words = ['map', 'art', 'how', 'rat', 'tar', 'who', 'pam', 'shoop'];
const groupedAnagrams = this.getGroupedAnagrams(words);
for (const sortedWord in groupedAnagrams) {
console.log(groupedAnagrams[sortedWord].toString());
}
return (
// Body elements
);
}
}
export default Anagram;
So, the first function takes in a string and splits it apart and creates an alphabetized string. Then, the next function takes in an array of strings, then for each word in the array it runs the word through the first function, then checks if the anagrams object already contains that "key". And if it does, then it pushes the original word into the array of that alphabetized word. If it doesn't contain that word, then it adds that "key".
My problem is that all the areas that have [sortedWord] return the error:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}'.
What have I done wrong? The project won't compile correctly until this error is fixed.
Upvotes: 0
Views: 460
Reputation: 337
'word' is of the type 'any'. When you use the return from alphabetize() and set it as an index for traversing anagrams.
anagrams[sortedWord]
Change the code to this, and it will work:
alphabetize(word: string) {
if (word) {
let words = word.split('');
words = words.sort();
word = words.join('');
return word;
}
return;
}
getGroupedAnagrams(words: string[]) {
const anagrams = {} as any;
words.forEach((word) => {
const sortedWord = this.alphabetize(word);
if (sortedWord) {
if( anagrams[sortedWord]){
return anagrams[sortedWord].push(word);
}
anagrams[sortedWord] = [word];
}
});
return anagrams;
}
Best doc for typescript: https://www.typescriptlang.org/docs/home.html
Upvotes: 1