0

Hello I have a small problem to understand Typescript and how to create a Object with properties.

I dont't understand how I can create a Object and after creation add some values in it.

I read many blogs with possible solutions but nothing worked. All I get is "Cannot set property 'bookTitle' of undefined".

I already tried this solutions. TypeScript and field initializers

How can I create an object based on an interface file definition in TypeScript?

In Typescript how to fix Cannot set property 'first' of undefined

At least I know that I have not fully understand how Typescript works and how I should fix it. It is a little bit frustrating to learn this language. I have only experience in Java...

My example code

//one ts file
 export interface Book {
   bookTitle: string;
   currentStatus: string;
   daysLeft: number;
   preregistrationStatus: string;
   returnDate: string;
   signature: string;
 }

 export class Lib {
   books: Array<Book>;

 ionViewDidLoad(): void {
  this.getBorrowedBooks();
 }

 getBorrowedBooks(): void {
  this.api.get('library/borrowedbooks')
  .map(res => res.json())
  .subscribe(
    data => {
      for ( let _i: number = 0; _i < data.length; _i++) {
        this.metaInfo.set( data[_i].bookTitle, data[_i].daysLeft);
       var book: Book = {
        bookTitle: data[_i].bookTitle,
        currentStatus: data[_i].bookTitle,
        daysLeft: data[_i].bookTitle,
        preregistrationStatus: data[_i].bookTitle,
        returnDate: data[_i].bookTitle,
        signature: data[_i].bookTitle,
      };
     this.books.push(book);
  }
 }

//Edit

Response Body

[
  {
    "bookTitle": "Mobile computing / Fuchß, Thomas , 2009 ",
    "returnDate": "2018-03-04",
    "currentStatus": "2. Verlängerung ",
    "signature": "2009 A 3032;h",
    "daysLeft": 21,
    "preregistrationStatus": ""
  }
 ]
4
  • There's a typo --> export inteface Commented Feb 12, 2018 at 17:56
  • This has to do with the response from library/borrowedbooks. Do you have an example of the response? Commented Feb 12, 2018 at 18:04
  • sry for typo -> typo fixed and i added my Response Body Commented Feb 12, 2018 at 18:12
  • Your code looks like it should be working. Are you able to log the value of data[_i] at the beginning of each iteration of the for loop and verify that data[_i] is the value you expect? The error message seems to indicate that data[_i] might be undefined in one of the loops. Commented Feb 12, 2018 at 18:20

1 Answer 1

0

Just initialize the property. Change:

books: Array<Book>;

to:

books: Array<Book> = [];

I have only experience in Java...

Look back and remember that you had to read up on the language to learn it. TypeScript is no different and a good book would help you immensely.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.