typescript入门

2023-05-17  本文已影响0人  LL天HH土

我个人的理解:typescript就是在javascript的基础上添加了 类型声明机制、添加了接口枚举类型
作用:减少类型错误、增加代码提示、语义化代码

声明文件

声明文件是以.d.ts为后缀的文件,开发者在声明文件中编写类型声明,TypeScript根据声明文件的内容进行类型检查。(注意同目录下最好不要有同名的.ts文件和.d.ts,例如lib.tslib.d.ts,否则模块系统无法只根据文件名加载模块)

为什么需要声明文件呢?我们知道TypeScript根据类型声明进行类型检查,但有些情况可能没有类型声明:

项目集成typescript后,整个项目只会编译校验typescript文件,所以项目中要书写typescript

总结一下,TypeScript会在特定的目录读取指定的声明文件

变量声明

let isDone: boolean = false
let list: Array<number> = [1, 2, 3]
function add(x: number, y: number): number {
    return x + y;
}
interface Params {
  a: string
}

function sub(params: Params):void{
}

枚举

enum Direction {
  Up, // 默认 0
  Down, //默认 1
  Left = 4, // 默认 2,修改成4
  Right, //默认3
}

接口

interface SquareConfig {
  Color: string;
  Width?: number; // 可选
  readonly Age: number; // 只能在对象刚刚创建的时候修改其值
}

class Animals {
  public name:string;
  private age: number; // private变量只能在本类内访问
  protected sex: string; // protected 可以在子类中访问
  constructor(theName: string){
    this.name = theName
  }
  
  class Dog extends Animals {
    constructor(){
      super('dog')
    }
  }
}

模块

模式参考esModule

// demo.ts
export class Dog { ... }
export class Cat { ... }
export class Tree { ... }
export class Flower { ... }
export default const One = 1
import { Dog } from './demo.ts'
import * as Animals from './demo.ts'
import One from './demo.ts'

命名空间

namespace Animals {
  class Dog {}
}
const dog = new Animals.Dog()

declear声明文件

在 TS 中使用非 TS 编写的第三方库,需要有个 xx.d.ts 声明文件
关键字 declare 表示声明的意思,我们可以用它来做出各种声明

declare var // 声明全局变量
declare function // 声明全局方法
declare class // 声明全局类
declare enum // 声明全局枚举类型
declare namespace // 声明(含有子属性的)全局对象
interface 和 type // 声明全局类型
上一篇下一篇

猜你喜欢

热点阅读