美文网首页
typescript入门

typescript入门

作者: LL天HH土 | 来源:发表于2023-05-17 17:28 被阅读0次

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

    声明文件

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

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

    • 第三方包,因为第三方包打包后都是JavaScript语法,而非TypeScript,没有类型。
    • 宿主环境扩展,如一些hybrid环境,在window变量下有一些bridge接口,这些接口没有类型声明。

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

    • 第三方javascript库文件,如果本身有声明文件,则可以直接使用
    • 第三方javascript库文件,如果没有声明文件,则要在项目内书写响应的声明文件

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

    • 在内部项目中,TypeScript会读取tsconfig.json中的文件集合,在其中的声明文件才会被处理。
    • 读取node_modules中各第三方包的package.jsontypes或者typing指定的文件。
    • 读取@types目录下同名包的声明文件。

    变量声明

    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 // 声明全局类型
    

    相关文章

      网友评论

          本文标题:typescript入门

          本文链接:https://www.haomeiwen.com/subject/gfpisdtx.html