TypeScript

10,012 阅读2分钟

TypeScript有两个核心:定义任何东西时要注明类型,调用任何东西时要你检查类型

TS = JS + 类型

tsc编译

基于大部分浏览器不能识别TS文件,就需要先写好TS文件,再通过typescript compiler工具编译为JS文件

// tsconfig.json
{ "target":"es2016"} //把TS文件按照es2016的标准编译成JS

注明类型

  • 基本形式是 冒号 + 类型(首字母小写,不是大写)
const url:string = 'https://api.thecatapi.com/v1/images/search'
  • 获取元素可能不存在,用断言,在末尾用 as + 类型
const button = document.querySelector('button') as HTMLButtonElement;
  • 联合类型
const button: HTMLButtonElement | null = document.querySelector('button')

创建一个类,方便汇集和复用数据

class Cat{
    constructor(id, url, height, width){
        this.id = id;
        this.url = url;
        this.height = height;
        this.weight = weight;
    }
}

在类里面,需要提前给参数注明类型,基于API文档,也知道返回数据的类型

class Cat{
    id:string;
    url:string;
    height:string;
    width:string;
    constructor(id:string, url:string, height:string, width:string){
        this.id = id;
        this.url = url;
        this.height = height;
        this.weight = weight;
    }
}

iterface语法,为对象进行类型定义。在里面规定好属性名和属性值的类型,方便在创建对象的时候都可以复用这个接口。简化上面的代码

interface CatType{
    id:string;
    url:string;
    height:string;
    width:string;
    test?:boolean;  // 表示可有可无
}
class Cat implements CatType{
    id:string;
    url:string;
    height:string;
    width:string;
}

泛型

函数名后面加上尖括号和占位符名称(一般为T)

 // 为函数定义返回的内容类型 :Promise<T> 
async function getJSON<T>(url:string):Promise<T>{
    const response:Response = await fetch(url);
    const json:Promise<T> = await response.json();
    // 知道返回Promise 先不着急定义Promise返回内容里的类型
    return json;
}

明确占位符的内容

async function getData(){
    try{
        // 在尖括号里明确Promise里返回什么内容
        const json:CatType[] = await getJSON<CatType[]>(url);
    }
}

数组注明类型

// 在数组类型前面加一个类型,表示数组里面的元素类型
let numArr:number[] = [5, 2, 0];

let strArr:string[] = ['爱', '老虎', '油']

// 数组里是一个对象,在接口interface里写对象的类型,再声明
interface Dan{}
let objArr:Dan[] = [{}]