Typescript index.d.ts 详解

文章讲述了TypeScript中如何通过类型定义文件定义全局类型,扩展模块如axios配置和Vue组件,以及使用三斜杠指令声明不同文件类型的依赖。

简而言之,就是类型定义文件:

1、定义全局类型

2、给已知模块扩充属性,或者定义模块

全局变量用法

来先看看官网的定义:举例 · 声明文件 · TypeScript中文网 · TypeScript——JavaScript的超集

优点歧义?好像是声明了全局变量???官网示例如下:

//index.d.ts
declare namespace myLib {
    function makeGreeting(s: string): string;
    let numberOfGreetings: number;
}


//用法
let result = myLib.makeGreeting("hello, world");
console.log("The computed greeting is:" + result);

let count = myLib.numberOfGreetings;

实际上像上述用法是报错的,提示根本没有mylib的变量,实际上myLib声明的是全局类型:作为类型使用就可以:

  //用typeof将该命名空间的类型取出使用
  let result = myLib.makeGreeting
  const fn :typeof result=()=>{
    return ''
  }
 

扩展module

场景1:在使用axios的时候,某些类型需要全局添加上一些自定义的类型,例如loading效果

import axios from 'axios'
//给AxiosRequestConfig 类型扩充属性
declare module 'axios' {
  interface AxiosRequestConfig {
    showLoading?: boolean
    showError?: boolean
  }
}

//注意:import export不能和声明全局变量一起使用,出现import,会被识别为npm或UMD文件。就只能用import导入使用了
//declare let var count:number;

场景2:vue3初始化的时候会看到这段代码~ ,这种方式用于声明一些公共的类型。

//用于声明导出的vue后缀结尾的是组件
declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<{}, {}, any>
  export default component
}

场景3:我在react-scripts的类型库中看到的,声明css文件,图片格式的定义,这些原来都是已经定义好的~

declare module '*.png' {
  const src: string;
  export default src;
}

declare module '*.webp' {
    const src: string;
    export default src;
}

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
    SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;
}

declare module '*.module.css' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

declare module '*.module.scss' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

declare module '*.module.sass' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

三斜杠的使用

三斜线指令 · TypeScript中文网 · TypeScript——JavaScript的超集

// <reference path="..." />指令是三斜线指令中最常见的一种。 它用于声明文件间的 依赖

就是声明的各种文件类型包。例如react,node,xx.d.ts

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值