typeScript学习

116 阅读2分钟

1.基础类型

boolean;number;string;数组;元组;枚举;any;viod;null;undefined;never,object

元组: 元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同

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

// 元组访问越界,会使用联合类型代替
x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型

console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString

x[6] = true; // Error, 布尔不是(string | number)类型

void类型:通常用于申明无返回值的函数;在用于申明变量时,他只能被赋予null,undefined值

null,undefined类型:

两者各自有自己的类型分别叫做undefinednull;

这两个类型是所有类型的子类型,也就是可以把undefinednull类型赋值给number类型

never类型:

  • never类型表示的是那些永不存在的值的类型。
  • 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) {
    }
}

类型断言: 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript会假设你,程序员,已经进行了必须的检查。

// 断言的两种语法
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;

2.类 定义类的关键字为 class,后面紧跟类名,类可以包含以下几个模块(类的数据成员):

  • 字段:字段是类里面声明的变量。字段表示对象的有关数据。

  • 构造函数:类实例化时调用,可以为类的对象分配内存。

  • 方法:方法为对象要执行的操作。