TypeScript : Colon vs Equal To ( Angular Tutorial )

后端 未结 6 1817
Happy的楠姐
Happy的楠姐 2020-12-06 10:35

I am learning Angular4 and going through the tutorial examples.

https://angular.io/docs/ts/latest/tutorial/toh-pt1.html

I have the below code in the tutoria

6条回答
  •  佛祖请我去吃肉
    2020-12-06 10:58

    Look again at the AppComponent:

    export class AppComponent { 
      title = 'Tour of Heroes';
      hero: Hero = {
        id: 1,
        name: 'Windstorm'
      };
    }
    

    The first field definition:

    title = 'Tour of Heroes';
    

    is assigning a string value. Because that value is a string, TS can infer the type. The line is equivalent to:

    title: string = 'Tour of Heroes';
    

    The second field definition

    hero: Hero = {
      id: 1,
      name: 'Windstorm'
    };
    

    is assigning an object, which could be any type. So here, to get the most out of TS, we should be specific about the kind of thing it will be. It could also be written:

    hero: { id: number, name: string } = {...};
    

    In the Hero class, you're only setting types, no default values. The pattern is actually the same in both:

    name[: type][ = value];
    

    It's probably worth having a look in the TS handbook for more information about types and class definitions.

提交回复
热议问题