当前位置:网站首页>Do you use typescript or anyscript
Do you use typescript or anyscript
2022-06-11 06:38:00 【__ LeoZhang】
1. What is? TypeScirpt
1.1 TypeScript brief introduction
TypeScript It's an open source programming language developed by Microsoft , By means of JavaScript It is built by adding static type definition on the basis of .TypeScript adopt TypeScript Compiler or Babel Translated into JavaScript Code , Can run in any browser , Any operating system .
1.2 TypeScript and JavaScript The relationship between
TypeScript yes JavaScript A superset of , They are not affiliated ,TypeScript Expanded JavaScript Limitations of weakly typed languages , More module parsing methods and syntax sugar are added .TypeScript It is not a language that can run independently , Most of the time he was translated into JavaScript function , So you can simply think TypeScript It is equivalent to a compiler with more functions JavaScript.
1.3 Why use TypeScript
Conventional JavaScript It can fully meet the needs of complete application development , But in the scenario of large-scale project collaborative development or plug-in development JavaScript The weakness of weakly typed languages is exposed . because JavaScript Not a compiled language , It is not easy to implement good type constraints and type inference in the process of code writing . If the developer provides a JavaScript Rely on packages for other developers , Developers who use dependencies do not display and observe the type composition inside the dependency package , It is easy to see the following scenarios , The code is as follows :
// If the dependent package provides attributes foo And the expectation type is string
foo = 123 // Now apply foo The developer of the variable sets the numeric type for it
...
foo = false // Later, there are developers who set up boolean type
// This application method will result in the inability to determine the explicit type of the attribute in the code reading
// It will also lead to certain operational risks in summary ,JavaScript Language has some weaknesses in code maintainability , So the strongly typed TypeScript The syntax is just right for such development scenarios .TypeScript Strong type constraints and its interface oriented programming constraints can make TypeScript The application of syntax development has strong maintainability , The price is more code space .TypeScript Very suitable for plug-in providers 、 Depend on the library provider 、 be based on JavaScript And the engineering development and use of large-scale projects , So that doesn't mean it applies to everything JavaScript Transformation of the project .
1.4 TypeScript The cognitive misunderstanding of
1. The reason TypeScript Can be popular , Because its performance is better than JavaScript?
This is a big mistake , at present TypeScript The main usage scenarios of are Web field , We know from the above introduction
Any use TypeScript Scripted applications or games , Neither of them can run the application directly by running the language , It can be said that TypeScript It's a grammar , Not the running language . Direct operation TypeScript The kernel of has not been popularized yet , So the vast majority of TypeScript All projects need to be compiled once , What is ultimately implemented is JavaScript, So it does not represent a performance advantage .
TypeScript Language is popular , Because it is typed JavaScript, Provides better type traceability when reading in context , The editor plug-in can realize better prompts . Its module and namespace capabilities are more in line with the engineering front-end idea .
2. It was used TypeScript Is better than using JavaScript Better
This is a misunderstanding caused by many cognitive errors , Some companies are trying to catch up with the project structure of big factories , There is no purpose in Vue or React Implant in the project TypeScript modular , This kind of implantation did not help the project develop better , On the contrary, developers' misunderstanding of the language will make it useless . In application development where the technical architecture is not complex ,TypeScript The use of will increase the amount of code , So in simple project development , Simple use ES6-ES2022 The syntax is sufficient to meet the needs of engineering . Misusing types can also make TypeScript Lose its default meaning , In many projects, developers are not familiar with TypeScript, All but the basic types will appear :any The implementation of the , Lead to TypeScript become AnyScript, This is also a very bad phenomenon , because TypeScript The type system of is mainly used for iteration and maintenance projects , Finally running JavaScript Types do not appear in the source code .
2.TypeScript introduction
TypeScript The Chinese document address of is :TypeScript Chinese net · TypeScript——JavaScript Superset Subsequent sections may require document review .
2.1 Environment building
Open the command line tool of the computer to execute TypeScript Engine installation commands , The code is as follows :
npm install typescript -gAfter successful installation , Enter the engine version command in the command line tool to view the version number , The code is as follows :
tsc -vIf the version number appears, the installation is successful .
2.2 Create project
TypeScript After the engine is installed successfully , You can use engine commands in the code editor TypeScript Project initialization . The method of initializing the project is the same as that of initializing Node The project is similar to . Create any folder in the code editor , Open the folder in the command line tool , Enter initialization TypeScript The order of the project , The code is as follows :
tsc --initAfter the command is entered , The folder will be automatically generated with the name tsconfig.json The file of , The contents of the document are as follows :
{
"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": "./", /* 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": "./", /* 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. */
}
}This article only introduces the project configuration involved , The next in tsconfig.json file rootDir and outputDir To configure , The code is as follows :
{
"compilerOptions": {
"rootDirs":["./src"],
"outDir":"./dist",
...
}
}complete tsconfig.js For the description of the configuration file, see :tsconfig.json · TypeScript Chinese net · TypeScript——JavaScript Superset
2.3 HelloWorld The implementation of the
Create... In the project src Folder , stay src Create in folder index.ts file , Initialize... In file HelloWorld Content , The code is as follows :
let str:string = 'hello'
console.log(str)After coding, enter the compilation command in the command line tool , The code is as follows :
tscAfter the command is executed, you will find a... In the project folder dist Folder , This is the output directory just configured , The corresponding output will be displayed in the folder index.js file , The contents of the document , The code is as follows :
"use strict";
let str = 'hello';
console.log(str);You can open... In the command line tool dist Catalog , adopt NodeJS Run the file , The code is as follows :
node indexThe console will appear hello word , If this step is OK, it means TypeScript It can work on the local computer . According to the operation, it is known that TypeScript The main purpose of the engine is to TypeScript To build a JavaScript Code , Finally through different JavaScript Engine to run the final code .
3.TypeScript Detailed study of
3.1 type
TypeScript The most distinctive is its type system , Type makes TypeScript Become a grammar that tends to be more static , Its types are used as follows :
3.1.1 Type declaration
Use the following code to learn TypeScript The type of life , The code is as follows :
let str:string = ' character string '
let num:number = 123
let flag:boolean = true
let undef:undefined = undefined
let nul:null = null
console.log(str)
console.log(num)
console.log(flag)
console.log(undef)
console.log(nul)
// It should be noted that the module export method must be used , otherwise TypeScript The variable of this file will be considered as a global variable, which will cause the prompt of duplicate name error
export default {}stay TypeScript To declare basic type data in, you only need to add a lowercase type name after the variable name , The overall coding is in addition to JavaScript identical , It should be noted that once a specific type is set for a variable , This variable must use a single type , Otherwise, there will be a type error , The code is as follows :
let str:string = ' A string '
str = 123
console.log(str)
export default {}When you run this snippet , The console will display the following error :
[email protected] ts % tsc
src/error1.ts:2:1 - error TS2322: Type 'number' is not assignable to type 'string'.
2 str = 123
~~~
Found 1 error.A variable can support multiple types by creating multiple types , The code is as follows :
let arg:number|string = ' ha-ha '
console.log(arg)
arg = 123
console.log(arg)
// Report errors
// arg = truenever Types represent types of values that never exist . for example , never Type is the return value type of a function expression or arrow function expression that always throws an exception or does not have a return value at all ; The variable can also be never type , When they are bound by type protection that will never be true .
never A type is a subtype of any type , It can also be assigned to any type ; However , No, The type is never Can be assigned to never type ( except never Beyond itself ). Even if any It can't be assigned to never.
Here are some returns never Function of type :
// return never The function of must have an unreachable end point
function error(message: string): never {
throw new Error(message);
}
// The inferred return value type is never
function fail() {
return error("Something failed");
}
// return never The function of must have an unreachable end point
function infiniteLoop(): never {
while (true) {
}
}3.1.2 Array tuples and objects
stay TypeScript in , There are many ways to define arrays , The code is as follows :
let arr:number[] = [1,2,3]// Pure numeric array
let arr1:Array<number> = [4,5,6]// Pure numeric array
// let arr2:Array<string> = ['1',2,3] // This array triggers a compilation error
let tuple:[number,string,boolean] = [12,'ab',true] // This declaration creates a tuple object
// let tuple1:[number,string] = [12] // Tuples are declared with a fixed length and cannot be violated
console.log(arr)
console.log(arr1)
console.log(tuple)
export default {}This code case describes how to define TypeScript Array objects in , stay TypeScript Added tuple implementation for array type data in the world of , But its characteristics are mainly reflected in the compilation process , The types in the generated code will be restored to arrays , The code is as follows :
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let arr = [1, 2, 3]; // Pure numeric array
let arr1 = [4, 5, 6]; // Pure numeric array
// let arr2:Array<string> = ['1',2,3] // This array triggers a compilation error
let tuple = [12, 'ab', true]; // This declaration creates a tuple object
// let tuple1:[number,string] = [12] // Tuples are declared with a fixed length and cannot be violated
console.log(arr);
console.log(arr1);
console.log(tuple);
exports.default = {};Through two cases, it is found that TypeScript In the world of , If the array is a dynamic length , Then the type is fixed , If multi type array is supported, the length is fixed , Next, how to declare a dynamically typed array , We need to use any keyword . stay TypeScript Provided in any Keyword is used to denote any type . When an attribute cannot infer its future type at the time of definition or its future dynamic type situation will occur , You can use any type , The code is as follows :
// any For any type , Once the variable is defined as any, The future can be any type
let arg:any = 123
console.log(arg)
arg = ' character string '
console.log(arg)
arg = [1,'a',true]
console.log(arg)
// Create a dynamically typed array
let arr:any[] = [2,3,'a',false]
let arr1:Array<any> = [4,5,7,'d']
console.log(arr)
arr1.push('lalal')
console.log(arr1)Arrays and tuples are one of the common reference types in programming , Another more common data type is the object type , When TypeScript When using objects in , There are still many ways to define types , The code is as follows :
// object Is the most basic way to create object properties
let obj:object = {
name:' Xiao Ming ',
age:18,
sex:' male '
}
class Ren{
name:string
age:number
sex:string
constructor(name:string,age:number,sex:string){
this.name = name
this.age = age
this.sex = sex
}
}
// object It also applies to object-oriented type declarations
let r:object = new Ren(' floret ',20,' Woman ')
// When using explicit objects, you can directly use class Name as type
let r1:Ren = new Ren(' Xiao Huang ',21,' male ')
console.log(obj,r,r1)
export default {}This case is used to describe how to define the type of object , there object Equivalent to... In the object any type , Just declare that the variable represents an object , However, the internal content of the object cannot be described in detail , So the objects defined with this type are dynamic objects , In the future, you can dynamically add new attributes to it , The object and tuple types created with the class name , Its type is fixed , So when the object type used is , After specifying the object type , The editor can provide complete hints and descriptions for the internal structure of objects , Pictured :


Compare the two pictures and you will find , When referring to an object with a specific type , The editor can provide complete type hints for it .
3.1.3 function 、 Enumeration and interface
Function in TypeScript The way to use is very simple , Refer to the following function examples , The code is as follows :
function test(){
console.log(' Ordinary function ')
}
// Functions with parameters and no return value
function test1(name:string,age:number):void{
console.log(name,age)
}
// Functions with parameters and return values
function test2(name:string,age:number):string{
return `name The value of is :${name},age The value of is ${age}`
}
test()
test1(' Xiao Ming ',18)
// When the return value type is known, the type can be omitted , The type of this variable will be locked to string Other types are not allowed
let res = test2(' Xiao Huang ',20)
console.log(res)
export default{}Dynamic type JavaScript Although there is the concept of type in language , But it doesn't have the characteristics of static language ,TypeScript Enumerations in are very characteristic data structures in static languages , It is often used to describe different constant values , The code is as follows :
enum ErrorCode {
Success = 200,
NotFoundError = 404,
ServerError = 500,
UnauthorizedError = 401,
OtherError = -1
}
function getList(type:string):ErrorCode{
if(type == 'Success'){
return ErrorCode.Success
}else if(type == 'NotFoundError'){
return ErrorCode.NotFoundError
}else if(type == 'ServerError'){
return ErrorCode.ServerError
}else if(type == 'UnauthorizedError'){
return ErrorCode.UnauthorizedError
}else{
return ErrorCode.OtherError
}
}
let res1 = getList('Success')
let res2 = getList('NotFoundError')
let res3 = getList('ServerError')
let res4 = getList('UnauthorizedError')
let res5 = getList('Other')
console.log(res1,res2,res3,res4,res5)The usage scenarios of enumeration are not introduced , So let's talk about that TypeScript Medium interface. Students who have studied interface oriented programming are right interface The way of using is not strange , One interface Is a completely abstract object , One interface Can correspond to multiple class Implement its internal unimplemented methods , stay TypeScript in ,interface Mainly used for type description , The code is as follows :
let obj = {
name:' Xiao Ming ',
age:18,
sex:' male '
}
// When using the function to get the dynamic type variable ,getObj The return result of the does not describe its internal properties
function getObj():object{
return obj
}
let obj1 = getObj()
console.log(obj1)
interface User{
name:string,
age:number,
sex:string
}
function getObjType():User{
return obj
}
// In this case, the returned data will have the type description of the data
let obj2 = getObjType()
console.log(obj2)
// Read only property definition
interface Point{
readonly x:number,
readonly y:number
}
let point:Point = {x:10,y:10}
// here point Of x and y Can't change
// point.x = 5
// Data after restricted type cannot use attributes other than the specified type
// let point1:Point = {x:10,y:10,z:11}
interface Config{
entry:Array<any>,
output:string,
// This attribute can dynamically define attribute types other than unnecessary contents , After use, you can extend attributes to crude oil objects
[str:string]:any
}
let config:Config = {entry:[1,2],output:'./',name:'abc'}
console.log(config)
// Define function types
interface SelectFunc{
(pno:number,psize:number):Array<User>
}
// After defining the type, the function does not need to describe the return value and parameter type
let func:SelectFunc = function(pno,psize){
return [{name:' floret ',age:18,sex:' Woman '},{name:' The small white ',age:18,sex:' male '}]
}
let res = func(1,10)
console.log(res)In the use of TypeScript During business development , There may be a large number of dynamic objects , To better expose its types to developers ,interface The use of is necessary .
besides ,interface Multi type merging can be realized , The code is as follows :
interface User{
name:string,
age:number,
sex:string
}
interface Admin{
name:string,
password:string
}
type Person = User | Admin
// At this time arr The array can include either User The structure of can include Admin Structure
let arr:Array<Person> = [
{
name:' Xiao Ming ',
age:18,
sex:' male '
},
{
name:' Administrators ',
password:'123456'
}
]3.1.4 Generic
Generics are another soul tool of statically typed languages , This is reflected in the problems caused by the fact that statically typed languages must specify types when defining types , The code is as follows :
function test(arg:number):number{
return arg
}
function test1(arg:string):string{
return arg
}When the parameters and return types of a function are explicit , Functions with the same structure need to define multiple functions according to different types , In this case, it is easy to increase the complexity of the code and reduce the maintainability , This problem can be solved through generics .
// Can pass T Specifying generics ,T The type represented is the same as any Different , He will recognize the type passed in when the function is actually called
// The corresponding code prompt can be generated according to the type of call
function test<T>(arg:T):T{
return arg
}
// When a string is passed in , The return value type of this function defaults to string And cannot be changed
let res = test(' character string ')
console.log(res)
// When a number is passed in , The return value type of this function is set to number
let num = test(123)
console.log(num)
export default {}3.2 TypeScript Other applications
3.2.1 Decorator
With TypeScript and ES6 Class is introduced in , In some scenarios, we need additional features to support annotation or modification of classes and their members . Decorator (Decorators) It provides a way for us to add annotations through metaprogramming syntax on class declaration and members . Javascript The decorator in is currently in The second stage of the proposal collection , But in TypeScript It has been supported as an experimental feature .
Be careful The decorator is an experimental feature , It could change in future releases .
To enable experimental decorator features , You have to be on the command line or tsconfig.json I use experimentalDecorators Compiler Options :
Command line :
tsc --target ES5 --experimentalDecoratorstsconfig.json:
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
} Decorator Is a special type of declaration , It can be attached to a class declaration , Method , The accessor ), Property or parameter . Decorator use @expression This form ,expression Must be a function after evaluation , It will be called at run time , The decorated declaration information is passed in as a parameter .
Next, let's take a simple decorator example to understand the decorator in TypeScript How to use the , The code is as follows :
// Decorator
function FormatDate(){
return function(target:any,key:string,descriptor: PropertyDescriptor){
// Block the properties that the decorator applies set Method
descriptor.set = function(d:Date){
let year = d.getFullYear()
let month = d.getMonth()+1
let date = d.getDate()
let _this:any = this
_this['_'+key] = `${year}-${month}-${date}`
}
}
}
interface User{
name:string,
age:number,
[props:string]:any
}
class User{
// Automatically format the time through the decorator
@FormatDate()
set birthday(v){this._birthday = v}
get birthday():Date{ return this._birthday }
constructor({name,age,birthday}:User){
this.name = name,
this.age = age
this.birthday = birthday
}
}
let u = new User({name:' Xiao Ming ',age:18,birthday:new Date()})
console.log(u)
console.log(u.birthday)
export default {}
Next, a server-side case , A deeper understanding of the significance of decorators , The code is as follows :
interface MappingType{
[props:string]:any
}
interface GlobalThis{
requestMappings:MappingType
}
let _globalThis:GlobalThis = {
requestMappings:{}
}
function Controller(url?:string){
// console.log(url)
return function(target:any){
// Store public URL
target.prototype.baseURL = url
}
}
function Get(url?:string){
// console.log(url)
return function(target:any, propertyKey: string, descriptor: PropertyDescriptor){
// Save the access path of the function to the global object requestMappings Properties of the
if(_globalThis.requestMappings == undefined){
_globalThis.requestMappings = {}
}
_globalThis.requestMappings[propertyKey] = url
}
}
// Definition type
interface UserController{
[props:string]:any
}
// Define controller
@Controller('/user')
class UserController{
@Get('/hello')
hello():string{
return 'hello'
}
@Get('/test')
test():string{
return 'test'
}
}
// Define the controller execution function
function runController(controller:any,url:string){
// Split 2 Class url route
let urlArr:Array<string> = url.replace('/','').split('/')
// Get the... Of the current object baseURL
let baseURL = controller.baseURL.replace('/','')
// Get current url The access path corresponding to the second level of the global object
let methodURL = _globalThis.requestMappings[urlArr[1]]
// When the two access paths match at the same time
if(urlArr[0] == baseURL && urlArr[1] == methodURL.replace('/','')){
// Execute the controller function and return the result
return controller[urlArr[1] ]()
}
}
// Call the execution function to get the result
let res = runController(new UserController(),'/user/test')
console.log(res)
export default {}3.2.2 Modules and namespaces
TypeScript Module system and ESM There is almost no difference in the import and export of the module system , The characteristic content here is the concept of namespace . Be sure to pay attention to ,TypeScript 1.5 The nomenclature has changed . “ Internal modules ” Now it's called “ Namespace ”. “ External modules ” Now it's called “ modular ”, This is for the sake of ECMAScript 2015 The terms in are consistent ,( in other words module X { It's equivalent to the recommended writing namespace X { ).
Namespaces are used to disassemble code internally into separate modules , Functions and code blocks with different functions can be divided into namespaces , The code is as follows :
namespace StringUtils{
export const reverse = (str:string):string => {
let str1 = ''
for(let i = str.length-1;i>=0;i--){
str1+=str[i]
}
return str1
}
export const replaceAll = (str:string,replaceStr:string,targetStr:string):string => {
let reg = new RegExp(replaceStr,'g')
return str.replace(reg,targetStr)
}
}
let str = 'abcdefgabcdefg'
str = StringUtils.reverse(str)
str = StringUtils.replaceAll(str,'a','n')
console.log(str)You can spread namespaces across multiple files , Merge references in code , Transform the above case into a distributed file mode , The code is as follows :
// stay src Create under folder string-replace.ts Document and prepare the following contents
namespace StringUtils{
export const replaceAll = (str:string,replaceStr:string,targetStr:string):string => {
let reg = new RegExp(replaceStr,'g')
return str.replace(reg,targetStr)
}
}
// stay src Create under folder namespace.ts Document and prepare the following contents
/// <reference path="string-replace.ts" />
namespace StringUtils{
export const reverse = (str:string):string => {
let str1 = ''
for(let i = str.length-1;i>=0;i--){
str1+=str[i]
}
return str1
}
}
let str = 'abcdefgabcdefg'
str = StringUtils.reverse(str)
str = StringUtils.replaceAll(str,'a','n')
console.log(str)To ensure that dependencies can be fully loaded , Specify how to merge files at run time , Enter in the command line tool , The code is as follows :
tsc --outFile dist/namespace.js src/string-replace.ts src/namespace.ts3.2.3 d.ts How to use
stay TypeScript In the development of, many scenarios need type definitions , There are different type descriptions for code between different modules . This means that you need to .ts There are a lot of class or interface To ensure type support . In this case, it is easy for two modules to share the same type, resulting in repeated type declarations , here d.ts Documents come in handy . Here is a simple example to introduce .d.ts How files are used , The code is as follows :
// When src/test.ts When the following contents exist in
interface User{
name:string,
age:number,
birthday:Date,
[props:string]:any
}
let user:User = {
name:' Xiao Ming ',
age:18,
birthday:new Date(),
money:100
}
console.log(user)
export default {}When test.ts Contained in the User Type , stay test1.ts The same applies to User Type , The easiest way , The code is as follows :
//src/test1.ts Contents of the file
interface User{
name:string,
age:number,
birthday:Date,
[props:string]:any
}
let user1:User = {
name:' The small white ',
age:20,
birthday:new Date(),
money:100
}
console.log(user1)
export default {}At this point, you will find that there is useless code , At this time, many developers may export types through module loading , Finally, it becomes the following effect :
//src/user.ts
interface User{
name:string,
age:number,
birthday:Date,
[props:string]:any
}
export default User
//src/test.ts
import User from './user'
let user:User = {
name:' Xiao Ming ',
age:18,
birthday:new Date(),
money:100
}
console.log(user)
export default {}
//src/test1.ts
import User from './user'
let user1:User = {
name:' The small white ',
age:20,
birthday:new Date(),
money:100
}
console.log(user1)
export default {}You can extract types from external files in the form of file demolition , But this approach is building JavaScript Will generate useless empty modules , Because the type will be completely erased during language conversion , therefore interface In fact, the content in the end does not exist . It needs to be used d.ts The file .d.ts The function of a file is to describe the file type , By default, the type recognizer looks for node_modules/@types Folder for global type retrieval , Can be in tsconfig.json Configuration in file typeRoots To modify the d.ts Storage location of . The following will typeRoots Property , The code is as follows :
{
"typeRoots": ["./types"],
}Create... In the project types Folder , Create... In it index.d.ts file , Define... In the file User type , And will test and test1 The type references of the two files are removed , The code is as follows :
// types/index.d.ts
interface User{
name:string,
age:number,
birthday:Date,
[props:string]:any
}
// src/test.ts
let user:User = {
name:' Xiao Ming ',
age:18,
birthday:new Date(),
money:100
}
console.log(user)
export default {}
// src/test1.ts
let user1:User = {
name:' The small white ',
age:20,
birthday:new Date(),
money:100
}
console.log(user1)
export default {}4. summary
Through to TypeScript A simple understanding of language , It needs to be clear TypeScript The significance and advantages of language in practical application development ,TypeScript It is not a language that must be used in project development , It is more used in server development 、 Game development 、 Plug in development and other scenarios . In front-end application construction and business development scenarios ,TypeScript Often with JavaScript Syntax mix , Not all parts need type definition and type annotation , Not at all TypeScript Every feature in must be applied in the project development , Therefore, when using this language, you must analyze the usage scenarios and select the most appropriate part of the application , Don't follow blindly .
边栏推荐
- FPGA interview notes (IV) -- sequence detector, gray code in cross clock domain, ping-pong operation, static and dynamic loss reduction, fixed-point lossless error, recovery time and removal time
- ijkPlayer中的错误码
- Transfer Learning
- Redux learning (I) -- the process of using Redux
- 数组去重。。。。
- [reading this article is enough!!! Easy to understand] confidence level understanding (95% confidence level and confidence interval)
- 通过两种方式手写一个消息队列
- Why is it that the live video of the devices connected to easygbs suddenly cannot be played? Insufficient database read / write
- 统计某次操作(函数)耗时时长
- 022 basic introduction to redis database 0
猜你喜欢

NPM upgrade: unable to load file c:\users\administrator\appdata\roaming\npm\npm-upgrade ps1

Simple knapsack problem

CCS method of installing compiler

解决ffmpeg获取AAC音频文件duration不准

Teach everyone how to implement an electronic signature

Shandong University machine learning experiment 7 pca+ SVM face recognition

FPGA interview notes (IV) -- sequence detector, gray code in cross clock domain, ping-pong operation, static and dynamic loss reduction, fixed-point lossless error, recovery time and removal time

EasyGBS接入的设备视频直播突然全部无法播放是为什么?数据库读写不够

Redux learning (III) -- using Redux saga, writing middleware functions, and splitting reducer files

Vulhub 8.1-backdoor vulnerability recurrence
随机推荐
UEFI查找PCI设备
Alias the path with the help of craco
[turn] flying clouds_ Qt development experience
Use meshlab to sample the point cloud of CAD model and display it in PCL
The difference between call and apply and bind
572. 另一个树的子树
[]==! []
必读1:格局越大的人,越懂得说话
go的fmt包使用和字符串的格式化
C语言大战“扫雷”
Shuffleerror:error in shuffle in fetcher solution
socket. IO cross domain stepping pit
Multimedia框架解析之MediaExtractor源码分析(一)
Human gene editing technology and ethical issues behind it [personal view, for reference only]
个人常用软件及浏览器插件分享
Shandong University machine learning final 2021
Autojs, read one line, delete one line, and stop scripts other than your own
JS two methods to determine whether there are duplicate values in the array
动态import
山东大学项目实训之examineListActivity