TypeScript 中的非基础类型声明

5,625 阅读1分钟

前言

在使用 TypeScript 进行类型声明时,除了使用到 booleannumberstringArray 等基础类型,还会使用到 DOM 元素的声明,或者 setInterval 等常用方法的声明。自己刚开始使用 TypeScript 的时候,会对这些非基础类型的声明感到困扰,因此,本文将记录自己困扰过的 TypeScript 非基础类型的声明。

版本说明

  • TypeScipt 版本:TypeScript 3.1
  • PixiJS 版本:5.0.1;

非基础类型的声明

DOM 元素的类型声明

安装 TypeScript 时,默认会引入 lib.dom.d.ts 文件,该文件提供了 DOM 元素的类型,我们直接使用就可以。

// <div>
const div:HTMLDivElement = document.createElement('div');

// <img>
const img:HTMLImageElement = document.createElement('img');
const img:HTMLImageElement = new Image();

...

canvas 的类型声明

const canvas:HTMLCanvasElement = document.createElement('canvas');
const ctx:CanvasRenderingContext2D = canvas.getContext('2d');

setInterval 声明

let timer:number = setInterval(()=>{
    
},500);

arguments 声明

function fn(){
    let args: IArguments = arguments;
}

自定义类型的声明

嵌套数组的类型声明

// 自定义接口
interface Position {
    x:number;
    y:number;
}

// 声明一个嵌套数组
const positionArray:Array<Array<Array<Position>>> = [
     [
          {
               x:0,
               y:0,
          }
     ]
]

PixiJS 中的类型声明

const bg:PIXI.Sprite = new PIXI.Sprite();
bg.on('pointerdown',(e:PIXI.interaction.InteractionEvent):void=>{
    
});

总结

  • JavaScript 中有很多 内置对象,它们可以直接在 TypeScript 中当做定义好了的类型,而他们的定义文件,则在 TypeScript 核心库的定义文件 中。

参考链接

更多文章