I am currently in the process of developing an application using Ionic v3. Strangely, I am encountering issues with my interface when trying to assign a variable value returned by a function.
Here is an example that works without any problems:
export interface Quote {
title: string;
}
export class HomePage {
quote: Quote;
constructor(public navCtrl: NavController) {
var foo = { title: 'Lorem ipsum dorem.' };
this.quote = foo; // Successfully logs as {title: "Lorem ipsum dorem."}
}
}
However, when attempting to retrieve the value from a function, things start to malfunction. (Even with the same interface)
quote: Quote;
constructor(public navCtrl: NavController) {
// Retrieving and setting quote
this.quote = this.getQuote();
console.log(this.quote); // Outputs: {title: "Lorem ipsum dorem."}
}
// Retrieve random quote
getQuote(category: string = undefined) : object {
const quotes = [
{
title: 'Lorem ipsum dorem.'
},
{
title: 'Lorem ipsum dorem.'
},
{
title: 'Lorem ipsum dorem.'
}
];
if (category == undefined) {
return quotes[Math.floor(Math.random() * quotes.length)];
}
}
When attempting to package the app into an APK file, the following error message is displayed:
line: 21
Type 'object' is not assignable to type 'Quote'. Property 'title' is missing in type '{}'.
L20: // Retrieving and setting quote
L21: this.quote = this.getQuote();
L22: console.log(this.quote);
It seems like setting the value of this.quote within the function could be a possible solution. However, I am still curious as to why this approach is not functioning properly. Any help or insights would be greatly appreciated.