TypeScript学习
配置编译器:
1、npm i typescript -g
2、tsc init//生成配置文件
3、tsconfig.json文件:"target":"ES6",
将noEmitOnError注释解开
4、tsc --watch//监视所有ts文件(监视个别文件:tsc --watch index.ts),一旦ts文件有改变,则编译出来的js文件也会有相应的变化
注:在html文件里面引入的是ts文件编译后的js文件
常用编译参数:
声明
变量声明
let a: string//注意不要用String(string是基元,String是包装器对象)
function count(x:number,y:number){}//函数形参
变量类型:
1、js的变量类型:
undefined:用在函数中表示不能有返回值,但是可以利用默认返回的undefined
function demo():undefined{
}
const x=demo()
if(x){ console.log('done');
}
object:只能存储非原始类型(原始类型:number,string......)
Object:可以存储非原始类型和原始类型,但是不能存储null和undefined
定义对象方法:
let person:
{
name:string,
age?:number,[key:string]:any
}
person={name:'tom',gender:'男',city:'北京'}
//age?代表age项可以为空,[key:string]:any代表可以加任何属性,但是要求属性必须为string类型,属性的值可以为任何值(key可以换成任何单词,只要形式对就行)
2、新加类型:
any:任何类型,放弃类型检查
不用单独':any',但是如果把any的变量赋值给其他非any得变量,则这个变量也会变成any类型(在函数中如果不声明则默认为any)
function demo():any{
return 1
}
function demo2():any{
return 'hello'
}
unknown
其他功能相似与any,但是不能直接将unknown的值赋值给非any和unknown的变量,同时也不能使用赋值对应的数据类型可以用的函数(eg:string类型变量->str3.toUpperCase())
把unknown变量赋值给非any和unknown的变量(前提是unknown的值是string类型):
let a:unknown
a='hello'
let x:string
//第一种
if(typeof a==='string'){
x=a
}
//第二种
x=a as string
//第三种
x=<string>a
调用unknown对象所赋值的数据类型的函数:
let str3:unknown
str3='hello'
//第一种
(str3 as string).toUpperCase()
//第二种
str3 as string.toUpperCase()
//第三种
if(typeof str3==='string'){str3.toUpperCase()}
never:不能有值,用在函数限制不能有返回值,不能有具有可访问的终结点
never函数用法(就是不能结束或者不能正常结束,必须有错误的结束)(ps:在判断语句中如果有完全不可能的判断,则这个判断的值就为never类型):
//第一种:无限递归
function demo():never{
demo()
}
//第二种:抛出错误并终止程序
function demo():never{
throw new Error('程序运行异常')
let x=demo()
console.log(x)
void:限制函数没有返回值,同时不能利用函数的任何返回值做任何操作
(如果没有返回值则默认是return undefined,如果利用这个函数里面的undefined也会报错),可以接受return undefined/return
function demo():void{
return
}
fucntion demo1():void{
return undefined
}
tuple:元组
(相当于let arr3:[string,number,string])
let mytuple: [number, string];
mytuple = [42,"Runoob"];
//访问
console.log(mytuple[0])
enum:枚举
(可以将定义的枚举对象直接当做限制放在函数的形参里面,这样如果在定义函数或者调用函数的时候拼错枚举值会报错且定义的时候系统会有选项提示,增加代码拼写的正确性)注:这里面定义的值都是只读属性,不能修改值
默认枚举值:
const enum Direction{
Up,Down,Left,Right
}//默认为Direction.Up=0,Direction.Down=1......
function walk(data:Direction){
if(data===Direction.Up){
......
}
else if(data===Direction.Down){
......
}
自定义枚举值:
const enum Direction{
Up='up',
Down='down',
Left='left',
Right='right'
}
type:创建一个全新的类型
//第一种
type leixing=number//意思是leixing代表的是number数据类型
let a:leixing
a=100
//第二种
type Status=number | string//Status可以是数字类型也可以是字符串类型
let a:Status
a=123
a='hello'
//第三种
type Gender='男' | '女'//Gender只能是'男'或者'女'
let a:Gender
a='男'
a='女'
//第四种
type Area={
height:number;
width:number
}//相当于这个类是个含有height和width的对象
let a:Area={
height:123,//这里一定要是逗号不是分号
width:456
}
//第五种
type Area={
height:number;
width:number
}
type Address={
num:number;
ceil:number
}
type House=Area&Address//联合
const house:House={
height:123,
width:456,
num:444,
ceil:222
}
特殊情况:如果用type来声明函数返回类型为void则不会严格要求函数的返回值只能是undefined(type LogFunc=()=>void)
’interface
变量函数定义限制:
let count:(a:number,b:number)=>number
count=function:number,d:number):number{
return a+b
}
限制函数的参数类型和返回值类型
变量数组定义限制:
//第一种
let arr:string[]
arr1=['a','b']//要求数组里面的元素必须是string类型的
//第二种
let arr2:Array<number>
arr2=[1,2,5]//要求数组里面的元素必须是number类型的
//第三种
let arr3:[string,number,string?]
arr3=['a',1,'b']//要求三个元素分别的数据类型并且限制只能有三个元素,但是第三个元素可以为空
//第四种
let arr4:[string,number,...string[]]
arr3=['a',1,'b']//要求前面两个的数据类型,第三个开始往后都要求string类型,数量不限(可以为0个)
注:用小写->string,number,boolean 用大写->Array,Object
类声明
//完整版
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
//简写版
class Person{
constructor(public name:string,public age:number){}//相当于包括了name和age的定义和初始化
接口声明
只能有声明,一般被用来覆盖
interface Animal {
name: string;
sound: string;
makeSound(): void;
}
函数声明
//普通函数
function greet(name: string): string {
return "Hello, " + name;
}
//箭头函数
const greet = (name: string): string => "Hello, " + name;
(name:string)//声明形参类型
function greet():string//声明函数返回值类型
模块导入/导出
导出:
export class Person {
constructor(public name: string) {}
}
导入:
import { Person } from './person';
类型守卫
function isString(value: any): value is string {
return typeof value === 'string';
}
异步编程
async function fetchData():Promise<string>{
const response=await ...//接口请求
return response
}
错误处理
try {
throw new Error("Something went wrong");
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}