TypeScript基础学习 —— 基础类型

基本类型

  1、boolean

let isDone: boolean = false;

  2、number

let decLiteral: number = 6; //十进制
let hexLiteral: number = 0xf00d; //十六进制
let binaryLiteral: number = 0b1010; //二进制
let octalLiteral: number = 0o744; //八进制

  3、string

    可以使用双引号(")或单引号(')表示字符串。

let name: string = "bob";
name = "smith";

    还可以使用模版字符串,它可以定义多行文本和内嵌表达式。 这种字符串是被反引号包围(`),并且以${ expr }这种形式嵌入表达式

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 sentence: string = "Hello, my name is " + name + ".

" +
    "I'll be " + (age + 1) + " years old next month.";

  4、数组

    两种方式可以定义数组。 第一种,可以在元素类型后面接上[],表示由此类型元素组成的一个数组

let list: number[] = [1,2,3];

      第二种方式是使用数组泛型,Array<元素类型> :

let list: number[] = [1,2,3];

  5、元组 Tuple

    允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。比如你可以定义一对值分别为 string 和 number 类型的元组。

let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error

    当访问一个已知索引的元素,会得到正确的类型:

console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

    当访问一个越界的元素,会使用联合类型替代:

x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型
console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString
x[6] = true; // Error, 布尔不是(string | number)类型

  6、enum 枚举

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

    默认情况下,从0开始为元素编号。 你也可以手动的指定成员的数值。 例如,我们将上面的例子改成从1开始编号:

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'因为上面代码里它的值是2

  7、any 任意值

    有时候会想要为那些在编程阶段还不清楚类型的变量指定一个类型,我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查。 那么我们可以使用any类型来标记这些变量。

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

    当你只知道一部分数据的类型时,any类型也是有用的。 比如,你有一个数组,它包含了不同的类型的数据

let list: any[] = [1, true, "free"];
list[1] = 100;

  8、空值

function warnUser(): void {
    alert("This is my warning message");
}

    声明一个void类型的变量没有什么大用,因为你只能为它赋予undefinednull

let unusable: void = undefined;

  

 

 

原文地址:https://www.cnblogs.com/Lyh1997/p/10900740.html