0

I am trying to create a model from a call to an api that returns objects in the response.

I have a simple class but now there is an object in the model and I don't know how to create my class as the school->name property in not defined on my page and typescript is complaining.

export class User {
  title: string;
  first_name: string;
  last_name: string;
  school : object {
  name: string
 }
}

What is the correct syntax to add the school object

Thank you

2 Answers 2

1

You were close - you just leave out the word "object". Like this:

export class User {
    title: string;
    first_name: string;
    last_name: string;
    school: {
        name: string
    }
}

// Sample usage
const user = new User();

user.school = { name: 'Beacon Hills High School' }

You can also create a User with an object literal:

const user: User = {
    title: 'Mr',
    first_name: 'Student',
    last_name: 'Rik',
    school: { name: 'Beacon Hills High School' }
};
Sign up to request clarification or add additional context in comments.

3 Comments

When I did that it was still an error, I used ``` school = { name: '' } ```
@StudentRik did you tried mine? and let me know what error exactly you are getting.
@StudentRik - are you trying to create a User using an object literal? If so, I have added a working example of that to the answer. If you intend to only define the structure, you may want to switch from class to interface.
1

try this proper model creation way

export class User {
    title: string;
    first_name: string;
    last_name: string;
    school: School;
}

export class School {
    name: string;
}

let user = new User();
let school = new School();
school.name = 'Beacon Hills High School';
user.school = school;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.