当前位置: 代码网 > it编程>编程语言>Javascript > typeScript学习

typeScript学习

2024年08月06日 Javascript 我要评论
1.新建tsconfig.json配置文件通过在项目命令行窗口输入npx tsc --init命令,自动生成tsconfig.json配置文件tsconfig.json部分参数解释如下:"rootDir": "src", // 源代码所在的目录"outDir": "dist", //文件编译后存放在哪个目录下在命令行窗口输入npx tsc会编译整个项目项目编译后的架构如下:整个tsconfig.json代码如下:{ "compilerOptions": {

1.新建tsconfig.json配置文件

通过在项目命令行窗口输入npx tsc --init命令,自动生成tsconfig.json配置文件

tsconfig.json部分参数解释如下:

"rootdir": "src", // 源代码所在的目录

"outdir": "dist", //文件编译后存放在哪个目录下

在命令行窗口输入npx tsc会编译整个项目

项目编译后的架构如下:

整个tsconfig.json代码如下:

{
  "compileroptions": {
    /* visit https://aka.ms/tsconfig.json to read more about this file */

    /* projects */
    // "incremental": true,                              /* enable incremental compilation */
    // "composite": true,                                /* enable constraints that allow a typescript project to be used with project references. */
    // "tsbuildinfofile": "./",                          /* specify the folder for .tsbuildinfo incremental compilation files. */
    // "disablesourceofprojectreferenceredirect": true,  /* disable preferring source files instead of declaration files when referencing composite projects */
    // "disablesolutionsearching": true,                 /* opt a project out of multi-project reference checking when editing. */
    // "disablereferencedprojectload": true,             /* reduce the number of projects loaded automatically by typescript. */

    /* language and environment */
    "target": "es2016",                                  /* set the javascript language version for emitted javascript and include compatible library declarations. */
    // "lib": [],                                        /* specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* specify what jsx code is generated. */
    // "experimentaldecorators": true,                   /* enable experimental support for tc39 stage 2 draft decorators. */
    // "emitdecoratormetadata": true,                    /* emit design-type metadata for decorated declarations in source files. */
    // "jsxfactory": "",                                 /* specify the jsx factory function used when targeting react jsx emit, e.g. 'react.createelement' or 'h' */
    // "jsxfragmentfactory": "",                         /* specify the jsx fragment reference used for fragments when targeting react jsx emit e.g. 'react.fragment' or 'fragment'. */
    // "jsximportsource": "",                            /* specify module specifier used to import the jsx factory functions when using `jsx: react-jsx*`.` */
    // "reactnamespace": "",                             /* specify the object invoked for `createelement`. this only applies when targeting `react` jsx emit. */
    // "nolib": true,                                    /* disable including any library files, including the default lib.d.ts. */
    // "usedefineforclassfields": true,                  /* emit ecmascript-standard-compliant class fields. */

    /* modules */
    "module": "commonjs",                                /* specify what module code is generated. */
    "rootdir": "src",                                  /* 源代码所在的目录 specify the root folder within your source files. */
    // "moduleresolution": "node",                       /* specify how typescript looks up a file from a given module specifier. */
    // "baseurl": "./",                                  /* specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* specify a set of entries that re-map imports to additional lookup locations. */
    // "rootdirs": [],                                   /* allow multiple folders to be treated as one when resolving modules. */
    // "typeroots": [],                                  /* specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* specify type package names to be included without being referenced in a source file. */
    // "allowumdglobalaccess": true,                     /* allow accessing umd globals from modules. */
    // "resolvejsonmodule": true,                        /* enable importing .json files */
    // "noresolve": true,                                /* disallow `import`s, `require`s or `<reference>`s from expanding the number of files typescript should add to a project. */

    /* javascript support */
    // "allowjs": true,                                  /* allow javascript files to be a part of your program. use the `checkjs` option to get errors from these files. */
    // "checkjs": true,                                  /* enable error reporting in type-checked javascript files. */
    // "maxnodemodulejsdepth": 1,                        /* specify the maximum folder depth used for checking javascript files from `node_modules`. only applicable with `allowjs`. */

    /* emit */
    // "declaration": true,                              /* generate .d.ts files from typescript and javascript files in your project. */
    // "declarationmap": true,                           /* create sourcemaps for d.ts files. */
    // "emitdeclarationonly": true,                      /* only output d.ts files and not javascript files. */
    // "sourcemap": true,                                /* create source map files for emitted javascript files. */
    // "outfile": "./",                                  /* specify a file that bundles all outputs into one javascript file. if `declaration` is true, also designates a file that bundles all .d.ts output. */
     "outdir": "dist",                                   /* 文件编译后存放在哪个目录下 specify an output folder for all emitted files. */
    // "removecomments": true,                           /* disable emitting comments. */
    // "noemit": true,                                   /* disable emitting files from a compilation. */
    // "importhelpers": true,                            /* allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsnotusedasvalues": "remove",               /* specify emit/checking behavior for imports that are only used for types */
    // "downleveliteration": true,                       /* emit more compliant, but verbose and less performant javascript for iteration. */
    // "sourceroot": "",                                 /* specify the root path for debuggers to find the reference source code. */
    // "maproot": "",                                    /* specify the location where debugger should locate map files instead of generated locations. */
    // "inlinesourcemap": true,                          /* include sourcemap files inside the emitted javascript. */
    // "inlinesources": true,                            /* include source code in the sourcemaps inside the emitted javascript. */
    // "emitbom": true,                                  /* emit a utf-8 byte order mark (bom) in the beginning of output files. */
    // "newline": "crlf",                                /* set the newline character for emitting files. */
    // "stripinternal": true,                            /* disable emitting declarations that have `@internal` in their jsdoc comments. */
    // "noemithelpers": true,                            /* disable generating custom helper functions like `__extends` in compiled output. */
    // "noemitonerror": true,                            /* disable emitting files if any type checking errors are reported. */
    // "preserveconstenums": true,                       /* disable erasing `const enum` declarations in generated code. */
    // "declarationdir": "./",                           /* specify the output directory for generated declaration files. */
    // "preservevalueimports": true,                     /* preserve unused imported values in the javascript output that would otherwise be removed. */

    /* interop constraints */
    // "isolatedmodules": true,                          /* ensure that each file can be safely transpiled without relying on other imports. */
    // "allowsyntheticdefaultimports": true,             /* allow 'import x from y' when a module doesn't have a default export. */
    "esmoduleinterop": true,                             /* emit additional javascript to ease support for importing commonjs modules. this enables `allowsyntheticdefaultimports` for type compatibility. */
    // "preservesymlinks": true,                         /* disable resolving symlinks to their realpath. this correlates to the same flag in node. */
    "forceconsistentcasinginfilenames": true,            /* ensure that casing is correct in imports. */

    /* type checking */
    "strict": true,                                      /* enable all strict type-checking options. */
    // "noimplicitany": true,                            /* enable error reporting for expressions and declarations with an implied `any` type.. */
    // "strictnullchecks": true,                         /* when type checking, take into account `null` and `undefined`. */
    // "strictfunctiontypes": true,                      /* when assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictbindcallapply": true,                      /* check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    // "strictpropertyinitialization": true,             /* check for class properties that are declared but not set in the constructor. */
    // "noimplicitthis": true,                           /* enable error reporting when `this` is given the type `any`. */
    // "useunknownincatchvariables": true,               /* type catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysstrict": true,                             /* ensure 'use strict' is always emitted. */
    // "nounusedlocals": true,                           /* enable error reporting when a local variables aren't read. */
    // "nounusedparameters": true,                       /* raise an error when a function parameter isn't read */
    // "exactoptionalpropertytypes": true,               /* interpret optional property types as written, rather than adding 'undefined'. */
    // "noimplicitreturns": true,                        /* enable error reporting for codepaths that do not explicitly return in a function. */
    // "nofallthroughcasesinswitch": true,               /* enable error reporting for fallthrough cases in switch statements. */
    // "nouncheckedindexedaccess": true,                 /* include 'undefined' in index signature results */
    // "noimplicitoverride": true,                       /* ensure overriding members in derived classes are marked with an override modifier. */
    // "nopropertyaccessfromindexsignature": true,       /* enforces using indexed accessors for keys declared using an indexed type */
    // "allowunusedlabels": true,                        /* disable error reporting for unused labels. */
    // "allowunreachablecode": true,                     /* disable error reporting for unreachable code. */

    /* completeness */
    // "skipdefaultlibcheck": true,                      /* skip type checking .d.ts files that are included with typescript. */
    "skiplibcheck": true                                 /* skip type checking all .d.ts files. */
  }
}

2..d.ts文件是什么?

.d.ts文件是ts用来声明变量,模块,type,interface等内容的
在.d.ts声明变量或者模块等东西之后,在其他地方可以不用import导入这些东西就可以直接使用,而且有语法提示。
创建了.d.ts文件还需要在tsconfig.json文件里面的include数组里面添加这个文件。include数组里面可以不用写.d.ts文件的绝对路径,可以通过glob通配符,匹配这个文件所在的文件夹或者是“祖宗级别”文件夹。
支持的glob通配符有:
*:匹配0或多个字符(不包括目录分隔符)
?:匹配一个任意字符(不包括目录分隔符)
**/:递归匹配任意子目录

应用示例如下:

 

3.declare

.d.ts 文件中的顶级声明必须以 declare 或 export 修饰符开头。
通过declare声明的类型或者变量或者模块,在include包含的文件范围内,都可以直接引用而不用去import或者import type相应的变量或者类型。
d.ts文件顶级声明declare最好不要跟export同级使用,不然在其他ts引用这个.d.ts的内容的时候,就需要手动import导入了
声明的方法或者类里面的方法是不能有具体的实现的。

参考链接:https://blog.csdn.net/weixin_41897680/article/details/127948971?ops_request_misc=&request_id=&biz_id=102&utm_term=ts中declare%20type&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-0-127948971.nonecase&spm=1018.2226.3001.4187

 

 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com