简体   繁体   中英

Variable declaration in typescript

I am confused about variable declartion inside angular component and want to know the purpose why we are declaring it in below way

 export class AppComponent {
  serverElements = [];
  newServerName = '';
  newServerContent = '';
}

and why we are not using type declartion here of typescript.

...want to know the purpose why we are declaring it in below way...

Those are property declarations with initializers. The resulting properties will exist on instances of the class (and will be public, just as though they had public in front of them).

...and why we are not using type declartion here of typescript...

TypeScript will infer the types from the initialization values (more in the documentation ). If you're initializing something when you're defining it, you often don't need to explicitly provide the type.

That said, there should be a type for serverElements since it will end up being never[] (in an up-to-date version of TypeScript), which probably isn't what the author wanted. For instance, if it was supposed to be an array of ServerElement instances:

export class AppComponent {
  serverElements: ServerElement[] = [];
  newServerName = '';
  newServerContent = '';
}

newServerName and newServerContent are both inferred as string , which is reasonable.

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