TypeScript 入门自学笔记
WEB前端开发社区 今天
什么是TypeScript?
是添加了类型系统的 JavaScript,适用于任何规模的项目。 是一门静态类型、弱类型的语言。 完全兼容 JavaScript,且不会修改 JavaScript 运行时的特性。 可以编译为 JavaScript,然后运行在浏览器、Node.js 等任何能运行 JavaScript 的环境中。 拥有很多编译选项,类型检查的严格程度可通过配置文件决定。 可以和 JavaScript 共存,这意味着 JavaScript 项目能够渐进式的迁移到 TypeScript。 增强了编辑器(IDE)的功能,提供了代码补全、接口提示、跳转到定义、代码重构等能力。 拥有活跃的社区,大多数常用的第三方库都提供了类型声明,并且开源免费
JavaScript 的缺点
它没有类型约束,一个变量可能初始化时是字符串,又被赋值为数字。 由于隐式类型转换的存在,有些变量的类型很难在运行前就确定。 基于原型的面向对象编程,使得原型上的属性或方法可以在运行时被修改。
为什么使用 TypeScript?
安装
安装:npm install -g typescript,全局安装,可以在任意位置执行tsc
TypeScript 的特性
1、类型系统
TypeScript 是静态类型
// test.js
let foo = 1;
foo.split(' ');
// TypeError: foo.split is not a function 运行时会报错(foo.split 不是一个函数)
// test.ts
let foo: number = 1;
foo.split(' ');
// Property 'split' does not exist on type 'number'. 编译时报错(数字没有 split 方法),无法通过编译
TypeScript 是弱类型
console.log(1 + '1'); // 11
2、原始数据类型基本使用
let flag: boolean = false
let num: number = 15
let str: string = 'abc'
var a: null = null
var b: undefined = undefined
// 编译通过
let flag:boolean=new Boolean(false) // Type 'Boolean' is not assignable to type 'boolean'.
let num: number = new Number(15) // Type 'Number' is not assignable to type 'number'.
let str: string = new String('abc') // Type 'String' is not assignable to type 'string'.
// 编译通过
let flag: boolean = Boolean(false)
let num : number = Number(15)
let str : string = String('abc')
// 编译通过
数值
let decLiteral: number = 6;let hexLiteral: number = 0xf00d;let binaryLiteral: number = 0b1010; // ES6 中的二进制表示法let octalLiteral: number = 0o744; // ES6 中的八进制表示法let notANumber: number = NaN;let infinityNumber: number = Infinity;
var decLiteral = 6;var hexLiteral = 0xf00d;var binaryLiteral = 10; // ES6 中的二进制表示法var octalLiteral = 484; // ES6 中的八进制表示法var notANumber = NaN;var infinityNumber = Infinity;
字符串
let myName: string = 'Echoyya';let str: string = `Hello, my name is ${myName}.`; // 模板字符串
var myName = 'Echoyya';var str = "Hello, my name is " + myName + "."; // 模板字符串
空值 及(与Null 和 Undefined的区别)
function alertName(): void { alert('My name is Tom');}
let unusable: void = undefined;
let u: undefined = undefined;let n: null = null;
let num: number = undefined;
let u: undefined;
let str: string = u;
let vo: void= u;
// 编译通过
let u: void;let num: number = u; // Type 'void' is not assignable to type 'number'.let vo: void = u; // 编译通过
3、任意值
let str: string = 'abc';
str = 123;
// Type 'number' is not assignable to type 'string'.
// -----------------------------------------------------------------
let str: any = 'abc';
str = 123;
// 编译通过
let anyThing: any = 'hello';
anyThing.setName('Jerry');
anyThing.setName('Jerry').sayHello();
anyThing.myName.setFirstName('Cat');
console.log(anyThing.myName);
console.log(anyThing.myName.firstName);
// 编译通过
let something;
something = 'seven';
something = 7;
// 等价于
let something: any;
something = 'seven';
something = 7;
类型推论
以下代码虽然没有指定类型,但编译时会报错:
let data = 'seven';
data = 7;
// Type 'number' is not assignable to type 'string'.
let data: string = 'seven';
data = 7;
// Type 'number' is not assignable to type 'string'.
let data;
data = 'seven';
data = 7;
// 编译通过
联合类型
let data: string | number; // 允许 data 可以是 string 或 number 类型,但不能是其他类型
data = 'seven';
data = 7;
data = true;
// Type 'boolean' is not assignable to type 'string | number'.
function getLength(something: st
ring | number): number {
return something.length;
}
// length 不是 string 和 number 的共有属性,所以会报错
// Property 'length' does not exist on type 'string | number'.
// Property 'length' does not exist on type 'number'.
function getString(something: string | number): string {return something.toString();}
let data: string | number;
data = 'seven';
console.log(data.length); // 5
data = 7;
console.log(data.length); // 编译时报错
// Property 'length' does not exist on type 'number'.
对象的类型——接口
interface Person { name: string; age: number;}let p1: Person = { name: 'Tom', age: 25};
确定属性
interface Person {
name: string;
age: number;
}
let p1: Person = { // 缺少 age 属性
name: 'Tom'
};
// Type '{ name: string; }' is not assignable to type 'Person'.
// Property 'age' is missing in type '{ name: string; }'.
// -----------------------------------------------------------------
let p2 Person = { // 多余 gender 属性
name: 'Tom',
age: 25,
gender: 'male'
};
// Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
// Object literal may only specify known properties, and 'gender' does not exist in type 'Person'.
可选属性
interface Person {
name: string;
age?: number;
}
let p1: Person = { // 编译通过
name: 'Tom'
};
let p2: Person = { // 编译通过
name: 'Tom',
age: 25
};
let p3: Person = { // 报错(同上)
name: 'Tom',
age: 25,
gender: 'male'
};
任意属性
interface Person {
name: string;
age?: number;
[propName: string]: any;
}
let p1: Person = {
name: 'Tom',
gender: 'male'
};
interface Person {
name: string;
age?: number;
[propName: string]: string;
}
let p1: Person = {
name: 'Tom',
age: 25,
gender: 'male'
};
// Property 'age' of type 'number' is not assignable to string index type 'string
// Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
// Property 'age' is incompatible with index signature.
// Type 'number' is not assignable to type 'string'
interface Person {
name: string;
age?: number;
[propName: string]: string | number;
}
let p1: Person = { // 编译通过
name: 'Tom',
age: 25,
gender: 'male',
year:2021
};
只读属性
interface Person {
readonly id: number;
name: string;
age?: number;
[propName: string]: any;
}
let p1: Person = {
id: 89757,
name: 'Tom',
gender: 'male'
};
p1.id = 9527;
// Cannot assign to 'id' because it is a read-only property.
interface Person {
readonly id: number;
name: string;
age?: number;
[propName: string]: any;
}
let p2: Person = { // 第一次给对象赋值
name: 'Tom',
gender: 'male'
};
p2.id = 89757;
// Property 'id' is missing in type '{ name: string; gender: string; }' but required in type 'Person' 对 p2 赋值时,没有给 id 赋值
// Cannot assign to 'id' because it is a read-only property. id 是只读属性
数组的类型
类型 + 方括号 表示法
let arr: number[] = [1, 1, 2]; // 数组元素中不允许出现其他的类型
let arr1: number[] = [1, '1', 2]; // 报错:Type 'string' is not assignable to type 'number'.
let arr2: number[] = [1, 1, 2, 3, 5];
arr2.push('8');
//报错:Argument of type '"8"' is not assignable to parameter of type 'number'.
数组泛型
let arr3: Array<number> = [1, 1, 2, 3, 5];
用接口表示数组
interface NumberArray { [index: number]: number;}let arr: NumberArray = [1, 1, 2, 3, 5];
类数组
function sum() {
let args: number[] = arguments;
}
// 报错:Type 'IArguments' is missing the following properties from type 'number[]': pop, push, concat, join, and 24 more.
function sum() {let args: { [index: number]: number; length: number; callee: Function; } = arguments;}
function sum() {
let args: IArguments = arguments;
}
//其中 IArguments 是 TypeScript 中定义好了的类型,它实际上就是:
interface IArguments {
[index: number]: any;
length: number;
callee: Function;
}
any 在数组中的应用
let list: any[] = ['Echoyya', 25, { website: 'https://www.cnblogs.com/echoyya/' }, false];
赞 (0)