当前位置:网站首页>Introduction to typescript and basic types of variable definitions
Introduction to typescript and basic types of variable definitions
2022-06-23 08:17:00 【wendyTan10】
( One )TypeScript An introduction to the
know typeScript
TypeScript Official website :TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
GitHub Statement :TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Translate :TypeScript It's a type of JavaScript Superset , It can be compiled into ordinary 、 clean 、 complete JavaScript Code
Understand this sentence on the official website :
- As opposed to
TypeScript( abbreviation ts) yesJavaScript( abbreviation js) The enhanced ; - js All the features you have ,ts All for ; It follows ECMAScript Standards for , therefore ES6、ES7、ES8 Wait for the new grammar standard , It's all for ;
- And on the linguistic level , It's not just about adding type constraints , And it includes some grammatical extensions , For example, enumeration type (Enum)、 A tuple type (Tuple) etc. ;
- TypeScript While implementing new features , Always keep and ES Standard synchronization is even leading ;
- also TypeScript It will eventually be compiled as JavaScript Code , So you don't have to worry about its compatibility , You don't need to build with Babel Such a tool ;
- therefore , We can TypeScript Understood as more powerful JavaScript, Not only JavaScript More secure , And it has brought many easy-to-use features ;
TypeScript Compiler environment for
TypeScript It will eventually be compiled as JavaScript To run the , So we need to build the corresponding environment ;
We need to install... On the computer TypeScript, So you can get through TypeScript Of Compiler Compile it into JavaScript;
# Installation command npm install typescript -g
# View version tsc --version
TypeScript Operating environment
Two solutions to configure the view run :
- Mode one :webpack Configuration of : Click to browse coderwhy The article written by the author
- Mode two : Use ts-node, Direct operation ;
install ts-node:npm install ts-node -g
in addition ts-node Need to rely on tslib and @types/node Two bags :npm install tslib @types/node -g
Now? , We can go straight through ts-node To run the TypeScript Code for :ts-node math.ts
( Two ) Declaration of variables
stay TypeScript Variables defined in need to be specified identifier The type of . So the complete declaration format is as follows :
// Assign values according to the defined data types
var/let/const identifier : data type = assignment ;
const name:string = 'wendy';
The above is support JavaScript The schema definition of , You may not add data types , but typescript Its own characteristics help us infer the corresponding variable types ;
Like the one below name Initial assignment string After the type , Cannot be changed to non string type 
( Two )JavaScript and TypeScript Data type of
JavaScript and TypeScript Inclusion relationship between data types of :
(1) Basic data types and definitions :
- number type ;
- boolean type ;
- string type ;
- Array type ;
const list1:string[] = ['1', '22']; // Recommended const list2:Array<string> = ['1', '22']; // stay react There are often <div></div> Writing , To avoid conflict - Object type ;
- Symbol type ;
- null and undefined type ;
- any type ;
// any Type is a bit like a flattering TypeScript methods , Just don't define the type , Any type can be implemented let name:any = 'wendy'; name = 'Bond'; name = 14555; name = true; - unknown type
Before you type check it ,// unknown yes TypeScript A special type in , It is used to describe variables of uncertain type ; // be relative to any , Only for unknown After type safety testing , To allow specific operations to be performed . let score: unknown = 98; let num = Math.round(score); //errorubnknowA variable of type cannot perform any operation .
Only for unknown After type safety testing , To allow specific operations to be performed ;let score: unknown = 98; if(typeof score === "number") { let num = Math.round(score); // ok } - void type
// Function has no return value type ; function sum(num1: number, num2: number): void { console.log(num1 + num2); } - never type
never A type that represents a value that will never happen , For example, an infinite loop or a function that throws an error :// advance // Encapsulate a core function function handleMessage(message: string | number | boolean) { switch (typeof message) { case 'string': console.log("string How to handle message") break; case 'number': console.log("number How to handle message") break case 'boolean': console.log("boolean How to handle message") break default: const check: never = message } } // Functions that throw errors function loopErr(): never { throw new Error(); } - tuple type - A tuple type
const tInfo: [string, number, number] = ["why", 18, 18]; const item1 = tInfo[0]; // why, And the type is string type const item2 = tInfo[1]; // 18, And the type is numbertupleandArrayThe difference between arrays :const info:(string|number)[] = ["why", 18, 18]; const item1 = info[0]; // The type cannot be determined const tInfo: [string, number, number] = ["why", 18, 18]; const item2 = tInfo[0]; // Fixed time string type
(2) Supplement to type definition
Automatic derivation type :
// Add type annotation to the parameter : num1: number, num2: number
// Add type comments to the return value : (): number
// In development , In general, you can not write the type of return value ( Automatic derivation )
function sum(num1: number, num2: number) {
return num1 + num2
}
sum(123, 321); // The derived type is number
const names = ["abc", "cba", "nba"]
// item Derived from the context of , At this time, you can not add type annotations
// Functions in context : You can not add type annotation
names.forEach(function(item) {
console.log(item.split(""))
})
Type derivation item yes string type :
Definition of object type :
// Point: x/y -> object type
// {x: number, y: number}
function printPoint(point: {
x: number, y: number}) {
console.log(point.x);
console.log(point.y)
}
printPoint({
x: 123, y: 321})
Use of optional types :?
// Point: x/y/z -> object type
// {x: number, y: number, z?: number}
function printPoint(point: {
x: number, y: number, z?: number}) {
console.log(point.x)
console.log(point.y)
console.log(point.z)
}
printPoint({
x: 123, y: 321})
printPoint({
x: 123, y: 321, z: 111})
Use of union types : |
// number|string Joint type
function printID(id: number|string|boolean) {
// When using values of union type , Special care is needed
// narrow: narrow
if (typeof id === 'string') {
// TypeScript Help determine id It must be string type
console.log(id.toUpperCase())
} else {
console.log(id)
}
}
printID(123)
printID("abc")
printID(true)
Relationship between optional types and object types :
// When a parameter is an optional type , This parameter is equivalent to : type |undefined The type of Union
// message?: string Equate to message: string | undefined
function foo(message?: string) {
console.log(message)
}
The use of type aliases , Use type Keywords to define :
// type Used to define type aliases (type alias)
type IDType = string | number | boolean
type PointType = {
x: number
y: number
z?: number
}
function printId(id: IDType) {
}
function printPoint(point: PointType) {
}
(3) Type assertions use :
- Types of assertions
as();
Type assertions are used to force a variable to change its type at compile time , Usually used forJoint type,any,And parent-child classesAssertions between , Usually this happens when you know clearly that an entity has a more exact type than its existing type ; There are two forms of writing :value as type<type>value
let data : any = "Hello";
let len : number = (<string>data).length;
console.log(len);// Output 5
len = (data as string).length;
console.log(len);// Output 5
Examples of use :
// 1. Types of assertions as
const el = document.getElementById("why") as HTMLImageElement
el.src = "url Address "
// 2. Other cases : Person yes Student Parent class of
class Person {
}
class Student extends Person {
studying() {
}
}
function sayHello(p: Person) {
(p as Student).studying()
}
const stu = new Student()
sayHello(stu)
// 3. understand : as any/unknown
const message = "Hello World"
const num: number = (message as unknown) as number
- Use of non empty type assertions :
!
// message? -> undefined | string
function printMessageLength(message?: string) {
// if (message) {
// console.log(message.length)
// }
// vue3 Source code
console.log(message!.length)
}
printMessageLength("aaaa")
printMessageLength("hello world")
- Use of optional chains :
?
// ? Code is not required
type Person = {
name: string
friend?: {
name: string
age?: number,
girlFriend?: {
name: string
}
}
}
const info: Person = {
name: "why",
friend: {
name: "kobe",
girlFriend: {
name: "lily"
}
}
}
console.log(info.name)
// console.log(info.friend!.name)
console.log(info.friend?.name)
console.log(info.friend?.girlFriend?.name)
边栏推荐
- Configuration asmx not accessible
- How to solve the problem that flv video stream cannot be played and TS file generation fails due to packet loss?
- Basic use of check boxes and implementation of select all and invert selection functions
- Does huangrong really exist?
- 建立一有序的顺序表,并实现下列操作: 1.把元素x插入表中并保持有序; 2.查找值为x的元素,若找到将其删除; 3.输出表中各元素的值。
- Imperva- method of finding regular match timeout
- Copy image bitmap by C # memory method
- Odoo project sends information to wechat official account or enterprise wechat
- 观察者模式
- typeScript的介绍与变量定义的基本类型
猜你喜欢

Implementation principle and source code analysis of ThreadPoolExecutor thread pool

渲染效果图哪家好?2022最新实测(四)

vtk.js鼠標左鍵滑動改變窗比特和窗寬

What are the PCB characteristics inspection items?

坑爹的“敬业福”:支付宝春晚红包技术大爆发

transform的结构及用法

开源软件、自由软件、Copyleft、CC都是啥,傻傻分不清楚?

看了5本书,我总结出财富自由的这些理论

What are open source software, free software, copyleft and CC? Can't you tell them clearly?

走好数据中台最后一公里,为什么说数据服务API是数据中台的标配?
随机推荐
MySQL common skills
qt 不规则图形 消除锯齿
@What is the difference between controller and @restcontroller?
Implementation of AVL tree
Does huangrong really exist?
力扣(LeetCode)173. 二叉搜索树迭代器(2022.06.22)
INT 104_LEC 06
Vulnhub | DC: 3 |【实战】
C# richTextBox控制最大行数
Socket socket programming
复选框的基本使用与实现全选和反选功能
Multi-scale feature combination in target detection
C print zoom
What is edge cloud?
Image segmentation - improved network structure
Moodle e-learning platform fixes the session hijacking error that leads to pre authorized rce
Basic use of check boxes and implementation of select all and invert selection functions
[cross border e-commerce solutions] lighthouse will be used for pure IP expansion of new business - continuous efforts!
typeScript的介绍与变量定义的基本类型
C Scrollview scroll up or scroll down