Vissie
Vissie

Reputation: 777

Interface won't work on variable (Object) where the value is declared w/ a function (Return) - TypeScript

I'm building an App with Ionic v3. For some reason my Interface won't work when the variable value is returned with a function.

For example this works fine.

export interface Quote {
    title: string;
}


export class HomePage {

   quote: Quote;

   constructor(public navCtrl: NavController) {
       var foo = { title: 'Lorem ipsum dorem.' };
       this.quote = foo; // Logs as {title: "Lorem ipsum dorem."}
   }
}

But as soon as I get the value returned from a function. Things won't work. (Same interface, ect.)

quote: Quote;

constructor(public navCtrl: NavController) {
   // Get & set qoute
   this.quote = this.getQuote();
   console.log(this.quote); // Returns: {title: "Lorem ipsum dorem."}
}

// Get 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)];
    }
}

But as soon as I want to build the App as an APK it will say:

line: 21
  Type 'object' is not assignable to type 'Quote'. Property 'title' is missing in type '{}'.
  L20:  // Get & set qoute
  L21:  this.quote = this.getQuote();
  L22:  console.log(this.quote);

I guess I could simply set the value of this.quote in the function. But why is this not working? Thanks for the help.

Upvotes: 2

Views: 66

Answers (3)

lietutis
lietutis

Reputation: 201

the problem is with types. You define result as object:

getQuote(category: string = undefined) : object {..}

but it should be of type Quote:

getQuote(category: string = undefined) : Quote {

Upvotes: 2

Joel Richman
Joel Richman

Reputation: 1934

You are not using the interface. You should type the return value of getQuote to be of Quote and type the array as array of quote. Now TypeScript can properly enforce the integrity of the code. Something like this should work:

getQuote(category: string = undefined) : Quote {
    const quotes: Quote[] = [
        {
            title: 'Lorem ipsum dorem.'
        },
        {
            title: 'Lorem ipsum dorem.'
        },
        {
            title: 'Lorem ipsum dorem.'
        }
    ];

    if (category == undefined) {
        return quotes[Math.floor(Math.random() * quotes.length)];
    }
}

Upvotes: 2

John Montgomery
John Montgomery

Reputation: 7096

object in TypeScript is a general category that encompasses all objects. When you cast your object to object, the app can't see its properties any more, so it doesn't know that your object conforms to the interface.

To fix it, just change your function to getQuote(category: string = undefined) : Quote

Upvotes: 2

Related Questions