Typescript支持与Javascript几乎同样的数据类型:布尔值、数字、字符串,结构体等,此外Typescript还提供了很实用的枚举类型。python
let isDone: boolean = false;
和Javascript同样,Typescript中的数字都是浮点数。
Typescript中的数字支持二进制、八进制、十进制、十六进制。git
let binary: number = 0b1010; let octal: number = 0o744; let decimal: number = 6; let hex: number = 0xf00d;
单双引号均可以,github
let name: string = "bob"; name = 'smith';
支持跟C#同样的内嵌表达式,即便用反引号`包围内嵌字符串,而后以${}的方式嵌入变量:typescript
let name: string = `Gene`; let age: number = 37; let sentence: string = `Hello, my name is ${ name }. I'll be ${ age + 1 } years old next month.`
let list: number[] = [1, 2, 3];
或者这样定义:编程
let list: Array<number> = [1, 2, 3];
跟python中的元祖同样,固然跟C#中的元组更像(由于有元素的类型声明):数组
// Declare a tuple type let x: [string, number]; // Initialize it x = ['hello', 10]; // OK // Initialize it incorrectly x = [10, 'hello']; // Error
enum Color {Red, Green, Blue}; let c: Color = Color.Green;
枚举默认是从0开始为元素编号,也能够手动指定成员的数值:编程语言
enum Color {Red = 1, Green, Blue}; let c: Color = Color.Green;
或者所有指定元素编号:学习
enum Color {Red = 1, Green = 2, Blue = 4}; let c: Color = Color.Green;
能够经过枚举值得到枚举的名字:翻译
enum Color {Red = 1, Green, Blue}; let colorName: string = Color[2]; alert(colorName); // Green
一般为那些在编程阶段还不可以确认数据类型的变量指定为Any类型。这些值能够来自动态内容,好比用户输入或是第三方库。
这种状况下,咱们不但愿类型检查器对这些值进行检查而是直接让它们经过编译时的检查。
这时候可使用 any
类型:code
let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean
你可能以为 any
与 Object
的做用同样。可是,实际并非这样。
你的确能够给 Object
类型赋任何类型的值,而后你却不能在它上面调用任意方法(即便那个对象真的有这些方法)! 可是Any类型能够!
let notSure: any = 4; notSure.ifItExists(); // okay, ifItExists might exist at runtime notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) let prettySure: Object = 4; prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
当你只知道一部分数据的类型的时候, any
类型也颇有用。好比你有一个数组,数组内包含不一样类型(若是类型全都知道,但是用Tuple):
let list: any[] = [1, true, "free"]; list[1] = 100;
void
有点相似于 any
的反义词: 它表示没有任何类型。一般用在没有返回值的方法:
function warnUser(): void { alert("This is my warning message"); }
声明一个 void
类型的变量没啥用,由于你只能给它赋值 undefined
或是 null
:
let unusable: void = undefined;
let
let
是Javascript新添加的一个关键字,功能了var
相似,可是它们的做用域不同(详细本身查)。let
更像是其余语言中定义变量的关键字,因此尽可能用let
来替代var
。
注:原内容来自github上的官方Handbook,这里我只是作了精简加翻译。
写这个的目的是做为学习Typescript的笔记,固然发出来也是为了分享给对Typescript感兴趣的同窗。学Typescript,最好有编程语言基础,最好是学过Javascript或是C#。
另外:这里有人翻译的完整版。