当前位置:网站首页>Take you three minutes to get started typescript
Take you three minutes to get started typescript
2022-06-26 07:30:00 【Web frontend】
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 .

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 :
- ts Input directly in the file js file , stay html The file import ts file , It can be run directly in the browser .
- 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 .
- 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 .
- 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 .

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 :

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.
边栏推荐
- Crosslinked metalloporphyrin based polyimide ppbpi-h) PPBP Mn; PBP-Fe; PPBPI-Fe-CR; Ppbpi Mn CR product - supplied by Qiyue
- Oracle中计算除法——解决除数为零报错
- . Net 20th anniversary! Microsoft sends a document to celebrate
- Sanic based services use celery to complete dynamic modification timing tasks
- SQL
- Liujinhai, chief architect of zhongang Mining: according to the analysis of fluorite supply and demand, it is estimated that the fluorine coating market has great potential
- Young man, do you know the original appearance of kotlin association process?
- 数据中心灾难恢复的重要参考指标:RTO和RPO
- 5,10,15,20-tetra (4-methoxycarbonylphenyl) porphyrin tcmpp purple crystal; Meso-5,10,15,20-tetra (4-methoxyphenyl) porphyrin tmopp|zn[t (4-mop) p] and co[t (4-mop) p] complexes
- When asked during the interview, can redis master-slave copy not answer? These 13 pictures let you understand thoroughly
猜你喜欢

5,10,15,20-tetraphenylporphyrin (TPP) and metal complexes fetpp/mntpp/cutpp/zntpp/nitpp/cotpp/pttpp/pdtpp/cdtpp supplied by Qiyue

Redis (4) -- Talking about integer set

Tetra - (4-pyridyl) porphyrin tpyp and metal complexes zntpyp/fetpyp/mntpyp/cutpyp/nitpyp/cotpyp/ptpyp/pdtpyp/cdtpyp (supplied by Qiyue porphyrin)

GMP模型

Iron / zinc / copper / platinum metal complexes such as 5,10,15,20-tetra (4-hydroxyphenyl) porphyrin (THPP) / (thppfe) / (thppzn) / (thppcu) / (thpppt) - Qiyue R & D

C#实现给DevExpress中GridView表格指定列添加进度条显示效果——代码实现方式

Liquid crystal texture diagram of purple solid mm-tpp-10c methacrylic acid decanoxy tetraphenyl porphyrin and mm-tpp-12c methacrylic acid dodecanoxy tetraphenyl porphyrin - Qi Yue display
![[recommend an entity class conversion tool mapstruct, which is powerful and easy to use]](/img/7b/43becce42192fb5e0469465aa27a36.png)
[recommend an entity class conversion tool mapstruct, which is powerful and easy to use]

13. Mismatch simulation of power synthesis for ads usage recording

基于sanic的服务使用celery完成动态修改定时任务
随机推荐
How can I find the completely deleted photos in Apple mobile phone?
In interface testing, several methods to verify the success of deleting interfaces
Blue Bridge Cup embedded learning summary (new version)
A bold sounding and awesome operation - remake a Netflix
$a && $b = $c what???
执行npm install -g serve时报错权限权限问题解决方案
缓存使用
Jemter stress test - basic requirements - [teaching]
Massive log collection tool flume
Which of the top ten securities companies has the lowest commission fee and is the most safe and reliable?
Multisensor fusion sensing
C#/. Net phase VI 01C Foundation_ 02:vs2019 basic operations, excluding code files, smart tips, data types, differences between float and double, and differences between string and string
Redis系列——5种常见数据类型day1-3
PXRD, IR, TGA of two-dimensional porphyrin COF (POR COF) /cof (2D pdpor COF) - supplied by Qiyue
Item2 installation configuration and environment failure solution
蓝桥杯嵌入式学习总结(新版)
SQL query statement
The performance of iron and steel enterprises was expected to be good in January this year. Since February, the prices of products of iron and steel enterprises have increased significantly. A mighty
Alkynyl crosslinked porphyrin based polyimide materials (ppbpi-h-cr, ppbpi Mn cr.ppbpi Fe Cr); Metalloporphyrin based polyimide (ppbpi Mn, ppbpi FE) supplied by Qiyue
GMP模型