简体   繁体   中英

Typescript cannot find name error

I am currently developing a application with the Angular2, i created a small private object which will have the firstName and the lastName when i try to transpile the file from typescript to javascript i am getting an error stating

error TS2304: Cannot find name 'firstName'

My code is

export class AppComponent {

public ContactDetail = {firstName="xander",lastName ="xmen"};

}

Is their an possible way to solve this solution

Thanks in advance

You should get a bit more familiar with the TypeScript syntax.
It starts from the JavaScript syntax, so your object should look like this:

ContactDetail = {
  firstName:"xander",
  lastName:"xmen"
}

To fix errors with your syntax, you can use:

export class AppComponent {
  public ContactDetail: {firstName:string, lastName:string} = {firstName: "xander", lastName:"xmen"};
}

But to make your architecture more flexible, you can do something like this:

export class ContactDetail {
    firstName: string
    lastName: string;
}

export class AppComponent {
    public ContactDetail: ContactDetail
}

// USAGE
var myContact = new AppComponent;
myContact.ContactDetail = {firstName: 'xander', lastName: 'xmen'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM