TypeScript简介
TypeScript是JAVScript类型的超集,它可以编译成纯JavaScript。TypeScript可以在任何浏览器、任何计算机和任何操作系统上运行,并且是开源的。
本文章单纯是在自己的学习过程中更加牢固,记录技术胖的TypeScript从入门到精通视频教程-2020年新版学习视频的相关知识点笔记https://www.bilibili.com/video/BV1qV41167VD?p=8,如有侵权等,请私信我删除!
获取TypeScript
先检查是否有安装node和npm
在cmd用命令行
node -v
npm -v
安装
npm install -g typescript
编译
tec helloworld.ts
安装专门运行.ts文件的一种方式
npm install -g ts-node
运行
ts-node helloworld.ts
最新 10.4.0版本的
ts-node -T helloworld.ts (跳过类检查)
TypeScrip静态类型及对象静态类型
let count : 基础静态类型 = X;
例:let count : number = 1;
对象类型
对象基础用法
const xiaoJieJie : {
name:string,
age:number
} = {
name:'大脚',
age:12
}
可以用接口定义对象类型
interface Xiaojiejie {
uname: string,
age:number
}
调用接口:
const xiaohong : Xiaojiejie = {
uname:'小红',
age:18
}
console.log(xiaohong.uname)
数组类型
const Xiaojiejie : string [] = ['谢大脚','好嗲','djao']
类类型
class Person{}
//代表dajiao是属于Person{}类里面的常量
const dajiao : Person = new Person()
函数类型
const jianxiaojiejie :()=>string =()=>{return '付海华'}
类型注解和类型推断
工作使用问题
-
如果 ts 能够自动分析变量基础,就不需要做什么;
-
如果 ts 无法分析变量类型的话,就需要使用类型注释。
什么时候需要类型注释,就是当光标放在变量上出现any的情况下,需要加上类型注释;它自己能推断的时候就让它自己推断不能的时候业就要加上注释。
const one = 1;
const two = 2;
const three = one + two;
//当one、two 去掉number时,光标停在上面会出现any
function getTotal(one:number,two:number) {
return one + two
}
const total = getTotal(1,2)
const xioajiejie = {
name:'陆地',
age:18
}
函数参数和返回类型的注释
函数参数与返回类型都需要加注释,除了能类型推断出来,但为了程序的严谨性建议还是加上好些。
function getTotal(one:number,two:number) : number {
return one + two
}
const total = getTotal(1,2)
//void声明不可以有return,不然会报错
function sayHello(): void {
console.log('Hello World')
}
// 永远的得不到一个正常的值 或者死循环 用never
function errorFuntion() : never{
throw new Error()
console.log('Hello World')
}
// 对象
function add({one,two} : {one : number, two : number}) {
return one + two
}
const totla = add({one:1,two:2})
数组类型注释的方法
基础用法
const numberArr:number[] = [1,2,3]
const string : string[] = ['w','f','d']
const arr : (number|string)[] = [1,'sfdasf',2]
当多方面运用到时,可定义一个类型别名或类,方便进行调用
// type alias 类型别名
type Lady = {name:string,age:number}
class Madam {
name:string;
age:number;
}
const xiaojiejie : Madam[] = [
{name:'刘鑫', age:12},
{name:'法师', age:28}
]
元组的使用
在一般工作使用对象比较多,元组就少些
const xiaojiejies : [string,string,number][] = [
['妲己','teacher',23],
['哈维','teacher',26],
['方家爱','teacher',25],
]