角度2中":"和""之间的差异

wha*_*ard -1 typescript angular

在角度2中,我注意到有几种方法可以=使用:和使用和声明变量public.

例:

  public heroes = HEROES;
  title = "Tour of Heroes";
  selectedHero: Hero;
Run Code Online (Sandbox Code Playgroud)

有什么不同 ?它只是关于初始化和未初始化?

Abd*_*yer 5

因为javascript没有type checking意义你可以做someVar="hello",以后你可以分配另一种类型的值,例如boolean like someVar=true,这在javascript中很好.类型脚本为javascript提供了其他功能的类型检查功能.这与初始化无关.

  • = 设置变量的值
  • : 设置变量的类型

在你的例子中:

public heroes = HEROES;  // assigns value of HEROES to heroes, heroes now has an inferred type same as the type of HEROES
title = "Tour of Heroes"; // normal assignment with inferred type of 'string'
selectedHero: Hero; // just declares selectedHero with the type 'Hero'
Run Code Online (Sandbox Code Playgroud)

您可以同时设置值和类型:

title:string = "some text"; // this means, title is of type string and has the value "some text"
Run Code Online (Sandbox Code Playgroud)

如果你这样做, title=true编译器会给你一个警告,因为你试图将boolean值赋给一个带有string类型的变量.

额外 您还可以设置多种类型而不是一种:

title:string|boolean=true; // title is of type either string or boolean
title:"text1"|"text2"|"text3"; // (v1.8 and after) title is of type string and can have only one of the values: "text1","text2" or "text3". in other words enum type 
title:any; // title is of any type.
Run Code Online (Sandbox Code Playgroud)

关于功能声明:

someFunction(name:string):boolean{
    // the parameter 'name' is expected to be of type string in the body of this function

    return true; // the return type of the function is expected to be boolean
}
Run Code Online (Sandbox Code Playgroud)

Lambda表达式:

someFunction = (name:string):boolean => {
    // the variable name is expected to be of type string in the body of this function
    return true;
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读:
类型打字稿类型系统的打字稿规范