基础类型

时间:2021-06-28 19:46:36   收藏:0   阅读:0

基础类型

布尔值

let isDone: boolean = false;

数字

let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;

字符串

let name: string = "bob";
name = "smith";
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];

元组 Tuple

// Declare a tuple type
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)类型

枚举

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;

枚举类型提供的一个便利是你可以由枚举的值得到它的名字。 例如,我们知道数值为2,但是不确定它映射到Color里的哪个名字,我们可以查找相应的名字:

enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];

alert(colorName);  // 显示‘Green‘因为上面代码里它的值是2

任意值

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
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‘.
let list: any[] = [1, true, "free"];

list[1] = 100;

空值

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

Null 和 Undefined

// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;

注意:我们鼓励尽可能地使用--strictNullChecks,但在本手册里我们假设这个标记是关闭的。

Never

下面是一些返回never类型的函数:

// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    while (true) {
    }
}

类型断言

类型断言有两种形式。

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

两种形式是等价的。 至于使用哪个大多数情况下是凭个人喜好;然而,当你在TypeScript里使用JSX时,只有as语法断言是被允许的。

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!