共计 2597 个字符,预计需要花费 7 分钟才能阅读完成。
前言
当我们在 TS 文件中需要引入外部库时,编译时是无法判断传入参数的类型的,所以我们需要在引入前加入一个声明文件来帮助 ts 判断类型。
当然现在大部分库都自带有自己的声明文件,一般在 @types 目录下。
使用场景
在 ts 文件中对引用的外部库做类型判断;
制作 npm 包时,书写自己的声明文件,需要在 package.json
的typing/types
字段注册声明文件的路径;
不使用 ts 时,也可以添加声明文件与(自己的)的模块存放在同一目录下,简单做一下数据结构体,对 IDE 参数声明也有用哦。
引用声明文件的几种方法
与调用的 ts 文件放在同一目录下;
在声明文件 tsconfig.json
的include/files
字段下添加声明文件的路径;
配置.eslintrc.js
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true,
},
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 12,
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
extends: ['plugin:vue/vue3-essential', 'plugin:vue/essential', 'eslint:recommended'],
plugins: ['vue', '@typescript-eslint'],
overrides: [
{
files: ['*.ts', '*.tsx', '*.vue'],
rules: {
'no-undef': 'off',
},
},
],
rules: {
'@typescript-eslint/ban-ts-ignore': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'vue/custom-event-name-casing': 'off',
'vue/attributes-order': 'off',
'vue/one-component-per-file': 'off',
'vue/html-closing-bracket-newline': 'off',
'vue/max-attributes-per-line': 'off',
'vue/multiline-html-element-content-newline': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/attribute-hyphenation': 'off',
'vue/html-self-closing': 'off',
'vue/no-multiple-template-root': 'off',
'vue/require-default-prop': 'off',
'vue/no-v-model-argument': 'off',
'vue/no-arrow-functions-in-watch': 'off',
'vue/no-template-key': 'off',
'vue/no-v-html': 'off',
'vue/comment-directive': 'off',
'vue/no-parsing-error': 'off',
'vue/no-deprecated-v-on-native-modifier': 'off',
'vue/multi-word-component-names': 'off',
'no-useless-escape': 'off',
'no-sparse-arrays': 'off',
'no-prototype-builtins': 'off',
'no-constant-condition': 'off',
'no-use-before-define': 'off',
'no-restricted-globals': 'off',
'no-restricted-syntax': 'off',
'generator-star-spacing': 'off',
'no-unreachable': 'off',
'no-multiple-template-root': 'off',
'no-unused-vars': 'error',
'no-v-model-argument': 'off',
'no-case-declarations': 'off',
'no-console': 'off',
'no-debugger': 'off',
},
};
实例
以外部库 fs 为例(假设 fs 没有自己的声明文件)
declare module 'fs' {
function readFileSync(path: string | number, options?: { encoding?: string; flag?: string; } | null): string;
}
import * as fs from 'fs'
const body = fs.readFileSync('../@types/fs.d.ts', {encoding: 'utf8'});
console.log(body);
总结
声明文件一般只能声明外部引入的 npm 包;
声明文件一定要用 declare module 'fs'
显式的声明自己的外部库名称;
原文地址: 【TS】TypeScript 声明文件(.d.ts)的使用
正文完