当前位置:网站首页>Take you three minutes to get started typescript

Take you three minutes to get started typescript

2022-06-26 07:30:00 Web frontend

TypeScript Is an open source software developed by Microsoft 、 Cross platform programming language , yes javaScript Superset , Finally compiled as javaScript Code . Often referred to as TS , Support JS、ES grammar .

TS Characteristics :

  • Began in javaScript belong to javaScript .
  • Powerful type system .
  • advanced javaScript .
  • Suitable for developing large projects , Compile to pure js Code ,js Can run on any browser .

 Take you 3 Minute quick start typeScript_typescript

typeScript Is a case sensitive language , This article mainly takes you to understand ts Installation , Environment configuration , And a simple introduction .

One 、 install TS

Installation is required before use :

      
      
npm install -g typescript
  • 1.

After installation , Use tsc -v Check the installed version .

first ts file :01.ts, The code is as follows :

      
      
(()=>{
function show(msg){
return " character string :"+msg
}
let str = " front end "
console.log(show(str))
})()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

adopt script introduce html file

      
      
<script src="./01.ts"></script>
  • 1.

The page is working properly , because ts Able to support js grammar , Therefore, it is no problem to directly import and use the file , besides , You can also use node Command to run the file , It can also be executed normally .

If at this time , stay ts Add... To the document ts grammar :

      
      
// Add type support
(()=>{
function show(msg:string){
// add to string The meaning of is the incoming msg Value can only be a string , It cannot be any other type
return " character string :"+msg
}
let str = " front end "
console.log(show(str))
})()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

When the browser is running , Will report a mistake , Unable to proceed with .

This is where you're going to have to put ts The file is compiled as js file , Open the command line tool , function :

      
      
tsc 01.ts
  • 1.

After running, it will automatically generate a 01.js file , see js The code content is as follows :

      
      
function show(msg) {
return " character string :" + msg;
}
(function () {
var str = " front end ";
console.log(show(str));
})();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

summary :

  1. ts Input directly in the file js file , stay html The file import ts file , It can be run directly in the browser .
  2. ts If any in the document ts Grammar code , If in html Introduce ts file , Running directly in the browser will report an error , At this point, you need to compile it into js file .
  3. stay ts Formal parameters in file functions , If a type is used for decoration , So in the final compilation js There is no such type in the file .
  4. ts Inland let Modifier , The compiled js The file becomes var .

Two 、Vscode Automatic compilation ts

Create a new project directory , Open the command line tool in the current directory , perform

      
      
tsc --init
  • 1.

Automatic generation tsconfig.json file , The code is as follows :

      
      
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "./js",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

notes :

outDir It means ts Generated after file compilation js Storage directory of documents . If the folder after the attribute value does not exist , It will automatically create .

strict Indicates strict mode .

newly build index.ts file , The code is as follows :

      
      
(() => {
function showStr(str:string) {
return str
}
let a: string = " Front end people "
// Call function
console.log("a",showStr(a));
})()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Type notes : The function terrain parameter is followed by a modifier , Used to restrict the type of the passed in parameter ,string The representation can only be of string type .

Run on the command line

      
      
tsc -w
// or
tsc -watch
  • 1.
  • 2.
  • 3.

Automatic generation js Folder , Include index.js file . After running the command , as long as ts The file has changed , It will automatically compile .

Everything is working normally , There are no mistakes .

If the parameter of the calling function is passed as a value :

      
      
console.log(showStr(123));
  • 1.

An error is reported in the editor : type “number” Argument to cannot be assigned to type “string” Parameters of .

 Take you 3 Minute quick start typeScript_typescript_02

ts Can intelligently prompt questions , Because ts Provides static code analysis , You can analyze the code structure and provide type annotations .

however tsc When compiling , Although it will prompt errors , But it will still compile to js file ,js No error will be reported during execution , because js It's a weakly typed language .

3、 ... and 、 introduction TS

Basic data type

  • boolean Is a Boolean value type . Such as :let isDone: boolean = false;
  • number Is the numerical type ,ts Able to support two 、 8、 ... and 、 Ten 、 Hexadecimal data . Such as :let decLiteral: number = 6;
  • string Is a string type . Such as :let name: string = "bob";
  • Represents array type . Array name followed by element type [] Add Array value . Such as :let list: number[] = [1, 2, 3];
  • A tuple type . Such as :let arr:[string,number,boolean] = ['str',1,true]
  • enumeration , Give a friendly name to a set of values . Such as :enum Color { red, green, blue }
  • Any type , Sometimes you are not sure what type of value is passed in , You can use any type . Such as :let notSure:any = 1
  • Null value , And any Just the opposite , Means there is no type of . Such as :function show():void { }
  • null and undefined
  • never type , A value that never exists .function error(message: string): never { throw new Error(message); }

Interface

An interface is simply a constraint . stay ts in , The purpose of an interface is to name these types and define contracts for your code or third-party code .

TypeScript The interface in is a very flexible concept , In addition to being able to abstract part of a class's behavior , It's also often used to correct 「 The shape of the object (Shape)」 Describe .

Use form :

      
      
(() => {
// Define an interface
interface Person{
firstName:string,// Add type qualification
lastName:string
}
function showFullName(person:Person) {
// After adding type qualification , The fields in the interface will be prompted automatically
return person.firstName + '_' + person.lastName
}
const p = {
firstName: "Hello",
lastName: "World"
}
console.log(" full name ",showFullName(p));
})()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

If you put p Medium firstName Comment out , You're going to report a mistake , Tips :

 Take you 3 Minute quick start typeScript_typescript_03

In this example , The meaning of an interface is to restrict the incoming showFullName Restrictions on data attributes within functions .

Interface advantages : Automatically detect whether the incoming data conforms to the interface specification , If not, an error will be reported .

class

Typescript Class introduction

Conventional JavaScript Our program uses functions and prototype - based inheritance to create reusable components , But it's a bit tricky for programmers who are familiar with the object-oriented approach , Because they use class - based inheritance and objects are built from classes ECMAScript 2015, That is to say ECMAScript 6 Start ,JavaScript Programmers will be able to use a class based object-oriented approach . Use TypeScript, We allow developers to use these features now , And compiled JavaScript Can run on all major browsers and platforms , You don't have to wait until the next JavaScript Version of .

ts The class of is just a syntax sugar , In essence js Functionally implemented .

Examples of use :

      
      
(() => {
// Define an interface
interface Person{
firstName: string,
lastName:string
}
// Define a class
class Personal {
// Define common field properties
firstName: string
lastName: string
fullName: string
// Constructors
constructor(firstName: string,lastName:string) {
// Update attribute data
this.firstName = firstName
this.lastName = lastName
this.fullName = this.firstName + this.lastName
}
}

const p = new Personal(' you ',' good ')

function showFullName(person: Person) {
return person.firstName + person.lastName
}
console.log("p",showFullName(p));
})()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.


原网站

版权声明
本文为[Web frontend]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202171109067932.html