typescript
是一门新的语言,typescript是javascript的超集,他解决了javascript类型系统不足的问题,大大提高了代码的可靠程度。
说起typescript
,我们先说说强类型语言和弱类型语言的概念:
语言的安全方面分为强类型和弱类型语言
强类型:形参跟实参的类型必须得保持一致,不允许数据的隐式类型转换
弱类型:形参跟实参的类型不用保持一致,允许数据的隐式类型转换
那强类型语言有哪些优势呢?
1.可以在代码的编译阶段消灭大部分有可能存在的类型错误
2.代码更智能,编码更准确
3.重构代码更加牢靠(删除对象的属性会有所限制)
4.减少在代码层面上的类型判断
语言有强弱之分,那还有静态和动态之分,语言的类型检查方面分为动态类型语言和静态类型语言
静态类型语言:变量在声明时,它的类型就已经确定了不能在被改变
动态类型语言:只有在运行阶段才能明确变量的类型,而且变量的类型可以随时被更改
所以综上所述:
javascript
是脚本语言,不需要编译,可以直接在运行环境中运行,所以就没有类型检查环节,所以是弱类型动态语言。
基于现在前端项目越来越复杂,javascript
这种弱类型的动态语言开发起来越来越困难,所以typescript
就孕育而生,越来越多的大型项目开始使用typescript
来编写。
要使用typescript,首先先搭建typescript环境:
1.npm init -y
初始化package.json
2.npm i typescript --save --dev
安装typescript
3.创建ts
格式的文件,之后编写代码
4.使用npx tsc src/xxx.ts
可以把ts文件编译成js文件
当然,我们还可以使用ts的配置文件来实现项目的整体编译
1.npx tsc --init
初始化tsconfig文件夹
2.设置配置文件下的rootDir
和outDir
就配置好了输入输出文件
3.接下来直接运行 npx tsc
就直接编译到dist文件夹下啦!
那接下来我们来学习typescript
的基础知识吧!
const str: string = 'tom';
const num: number = Infinity;
const bool: boolean = false;
const arr: string[] = ['aaa'];
const emtpy: null = null;
const a: void = undefined;
const b: undefined = undefined;
const c: symbol = Symbol()
const obj: {name: string} = {name: 'tom'};
1.数组类型有二种方式
const arr: string[] = ['aaa'];
const arr1: Array<string> = ['aaa'];
2.元组类型
// 元素类型要一一对应,且个数相同
const arr2: [string] = ['aaa'];
const arr3: [string, number] = ['aaa', 123];
3.枚举类型
const enum postStatus{
aaa,
bbb,
ccc
}
const post = {
type: postStatus.aaa
}
4.函数类型
function fn1(name: string) {
return name
}
const fn2: (name: string) => string = name => name;
5.任意类型
function stringfy(string: any) {
return JSON.stringify(string)
}
6.类型断言
const arr4 = [100, 200, 300, 400];
const res = arr4.find(num => num > 200) as number
const num1 = res as number;
const sum = 100 + res;
const sum1 = 100 + num1;
7.接口
interface postType {
title: string
content: string
subTitle?: string
readonly summary: string
}
interface anyType {
[key: string]: string
}
const printPost = (post: postType) => {
console.log(post.title)
console.log(post.content)
}
8.类
public
内部跟外部都能使用;private
只能内部能使用;protected
内部跟子类可以访问
interface talkType {
talk (str: string): void
}
interface eatType {
eat(food: string): void
}
class Person implements talkType, eatType {
public name: string;
public age: number;
private readonly height: number;
constructor(name: string, age: number, height: number) {
this.name = name;
this.age = age;
this.height = height;
}
getHeight() {
return this.height;
}
talk(str: string) {
console.log(str)
}
eat(str: string) {
console.log(str)
}
}
9.泛型
泛型就是指我们在定义函数参数得时候,我们没有具体去指定她的类型,等到我们使用这个函数的时候才确定她的类型
// 定义了创建数字数组或者字符串数组等
function createArray<T> (length: number, value: T) {
const arr = Array(length).fill(value) as T[]
return arr
}