TypeScript
TypeScript是什么
- 以JavaScript为基础构建的语言
- 一个JavaScript的超集
- 可以在任何支持JavaScript的平台中执行 (TS不能被JS解析器直接执行)
- TypeScript扩展了JavaScript,并添加了类型
TypeScript增加了什么
- 类型
- 支持ES的新特性
- 添加ES不具备的新特性
- 丰富的配置选项
- 强大的开发工具
JS,ES,TS的关系
ECMAScript是JavaScript的标准,TypeScript是JavaScript的超集
TypeScript开发环境搭建
-
下载Node.js
-
安装Node.js
-
使用npm全局安装typescript npm i -g typescript
-
创建一个ts文件
-
使用tsc对ts文件进行编译
- 进入命令行
- 进入ts文件所在目录
- 执行命令:tsc xxx.ts
降级编译
tsconfig.json 中的target是可以降级编译的, 修改这个就可以完成降级编译
严格模式
- “strict”: true 可以判断全部
- “noImplicitAny”:true
- "stricNullChecks":true
判断null undefined
基元类型
string number boolean
let str:string = “hello word”
let num: number = 100
let bol :boolean = true
使用ts记得输入 tsc --init 指令 生成tsconfig.json 文件 为了显示方便可以在json文件中修改 入口文件Modules下的“rootDir”:“./xxx” 和输出文件夹 在Emit下的。“outDir”:“./xxx” tsc --watch 编译ts的指令
数组
两种写法
type[] Array<type>泛型写法
let arr:number[] = [1,2,3]
let arr2:Array<number> = [1,2,3]
any
不希望某个特定值导致类型检查错误,禁用所有类型检查
let obj
变量上的类型注释 let name: string = ‘hello’
函数
function greet(name:string):void {
console.log('hello')
}
括号里是参数类型注释。 void 返回值类型注释
function greet(name: string) {
console.log("hello" + name.toLowerCase() + "99");
}
greet("angle");
function getFavoriteNumber(): number {
return 24;
}
对象
function printName(obj: { first: string; last?: string }) {
console.log(obj.first.toLowerCase());
console.log(obj.last?.toLowerCase());
}
printName({ first: "Angle" });
printName({ first: "angle", last: "pp" });
联合类型
let id: number | string 两个或多个其他类型组成的类型就是联合类型
function welcomePeople(x: string[] | string) {
if (Array.isArray(x)) {
console.log("hello" + x.join("and"));
} else {
console.log("hello" + x);
}
}
welcomePeople(["hello"]);
welcomePeople("pp");
function getFirstThree(x: number[] | string) {
return x.slice(0, 3);
}
let f = getFirstThree("123456");
let a = getFirstThree([1, 2, 3, 4, 5, 6, 67, 8]);
console.log(f);
console.log(a);
类型别名
类型别名的意思就是用这个名字来代替定义的类型,类型别名的语法是用type后面跟一个类型的名字等于一个类型就可以了。如下:
type point = {
x: number;
y: string;
}; //可以是对象类型
function fn(obj: point) {}
fn({
x: 100,
y: "hello",
});
type ID = number | string; //联合类型
function fn1(id: ID) {}
fn1(10);
fn1("9");
type UserInputSanitizedString = string; // 基元类型
**type定义的是类型的名字 千万不要认为定义的是个变量后面的是个值**
function fn2(str: string): UserInputSanitizedString {
return str.slice(0, 2);
}
let userInput = fn2("hello");
userInput = "new Input";