当前位置:网站首页>Typescript learning notes (II)
Typescript learning notes (II)
2022-06-11 17:03:00 【Yangxiaoao】
Turn on ts Way of learning , This article ts The complex data types of 、 Literal type 、 return type 、 The remaining parameters and this.
One 、 Complex data type
Same as JS equally ,TS There are also complex data types , It includes the following :
- An array type Array
- A tuple type Tuple
- Special type any、unknown、void、undefined、null、never、object
Next, I will explain these data types .
1、 An array type Array
Each item of an array can actually define its field type :
let arr1: number[] = [1,2,3]
let arr2: string[] = ["1", "2", "3"]
If the specified value is not assigned , You're going to report a mistake :

The above code can also be expressed in this way :
let arr1: Array<Number> = [1,2,3]
let arr2: Array<String> = ["1", "2", "3"]
Be careful :
It is recommended that the first method be preferred , Otherwise, in the React Of JSX Possible conflicts in syntax . All of the following can use this kind of writing , I can't even talk about .
After that, all array operations must also conform to the above data type definitions :
let arr2: string[] = ["1", "2", "3"]
arr2.push("4"); // correct
arr2.push(4); // error
2、 Type inference
If each array item has a different value ,TS Will automatically prompt us :

This is type inference .TS Help us figure out how many data types there are in this array , So you can change the code to :
let arr: (string | number | boolean)[] = [" Xiao Yang ", 18, true]
such , Developers can write code intelligently .
3、 A tuple type Tuple
If every item in the array is also an array , How to write ? In this case, we need to rely on tuples Tuple.
The most important feature of tuples is that they can limit the number and type of array elements , It is especially suitable for implementing multivalued return . stay JavaScript There is no concept of tuples in , As a dynamically typed language , Its advantage is that it naturally supports multi type element arrays .
let arr: [string, number][] = [
[" Zhang San ", 13],
[" Li Si ", 14],
[" Wang Wu ", 15]
];
If each array item is not an array , But the object , So it's written as follows :
let arr: {
name: string, age: number}[] = [
{
name: " Liu bei ", age: 21},
{
name: " Guan yu ", age: 21},
{
name: " Zhang Fei ", age: 21}
]
4、 Any type any
any It refers to an arbitrary type , It is an official way to bypass static type detection . Such as :
let arr: any[] = [111, " Hello world "]
Be careful :
Don't use it unnecessarily any, This almost goes against TS Starting point .
5、 Uncertain variables unknown
unknown yes TypeScript 3.0 A type added to , It is mainly used to describe variables with uncertain types . stay 3.0 In previous versions , Only use any To meet this dynamic type scenario . And any The difference is ,unknown More secure in type . For example, we can assign any type of value to unknown, but unknown The value of type can only be assigned to unknown or any.
let str: unknown;
let num: string = str; // You can't type “unknown” Assign to type “string”.
let abc: any = str; // No report error
6、 No return value void
When a function does not return a value , Need to add void:
function fn(one: number, two: number): void{
console.log(123)
}
fn(1,2);
7、undefined And null
These two are relatively simple , Omit here .
8、never
never A type that represents a value that will never happen . One that will never have a return value , Or a function that produces an infinite loop , You can add never:
// Only when an error is reported will an error return be generated
function fn1(str: string): never {
throw Error(str);
}
// Only if the condition is true will the value return
function fn2(): never {
while(true) {
}
}
9、object
object Types represent types that are not primitive types , It's not number、string、boolean、bigint、symbol、null、undefined The type of .
10、 Types of assertions
If a paragraph js Code , You can already clearly know that the return value must be a certain data type , You can use as Assert it :
const arr: number[] = [1,2,3,4]
const result: number = arr.find(num=>num>2) as number;
5、 ... and 、 Literal type
stay TypeScript in , Literals can not only represent values , It can also represent the type , The so-called literal type .
Use the data type represented by the value as the data type of the variable , Simply speaking , namely : Values can also be used as types . But should pay attention to , At present, it can only be string、number and boolean Three data types can be written as literal types .
const str: " Hello world " = " Hello world ";
const num: 123 = 123;
const bool: true = true;
6、 ... and 、 return type
Tell me about void When , Actually, it has been used , As follows :
function fn(one: number, two: number): number{
return one + two;
}
fn(1,2);
7、 ... and 、 The remaining parameters
stay ES6 in ,JavaScript Support the remaining parameters of function parameters , It can collect multiple parameters into a variable . Again , stay TypeScript Such parameter type definitions are also supported in .
// The number of parameters is uncertain , But to achieve accumulation
function fn(num1: number, ...nums: number[]): number{
return nums.reduce((prev,next) => prev + next, num1);
}
console.log( fn(1,2) );
console.log( fn(1,2,3) );
The effect is as shown in the picture :

8、 ... and 、this
Native JS Medium this The point is very vague , Function this Only when the function is called can we know this Point to the who . and TS in , In strict mode... Must be explicitly specified this Point to , Otherwise, as shown in the figure below :

So the code should be changed to :
function fn(this: Window, str: string){
// here Window It's capital
console.log(this);
}
window.fn = fn; // here window It's lowercase
window.fn(" Hello world ");
Pay attention here :
1、 This code will not execute successfully , Because you are ts-node Operation in environment , non-existent window, There won't be global;
2、 there this It's pseudomorph , Will not be compiled as js.
边栏推荐
- 启牛推荐开通的股票账户安全吗?靠谱吗
- 《DAMA数据管理知识体系指南》:章节分值占比
- “is-a”,“has-a”,“like-a”
- What products are good for cross-border e-commerce? What are the top selling categories?
- CS0006 C# 未能找到元数据文件“C:\Users\...问题
- Web security - shooting range notes
- Real time myth -- real-time RTOS multitask performance analysis
- 多任务学习经典品读:MMoE模型篇
- solr(一)solr的安装及权限控制
- Development planning of China's stainless steel market and suggestions on the development direction of the 14th five year plan 2022-2028
猜你喜欢

一套ThinkPHP微信小程序商城源码带后台管理

2022 molten welding and thermal cutting work license and simulation examination

Create database instance

The micro service failed to connect to the cloud sentinel console and the link blank problem occurred after the connection was successful (resolved)

【pytest学习】pytest 用例执行失败后其他不再执行

LeetCode——42. 接雨水(双指针)

所见即所得的 markdown 编辑器:Typora

A journey of database full SQL analysis and audit system performance optimization

API management artifact that allows you to call wow directly

2022 high altitude installation, maintenance and demolition test simulation 100 questions and online simulation test
随机推荐
LeetCode——42. Connected to rainwater (double pointer)
How unittest knows the execution time of each test case
LeetCode——42. 接雨水(双指针)
数据库全量SQL分析与审计系统性能优化之旅
微服务连接云端Sentinel 控制台失败及连接成功后出现链路空白问题(已解决)
Oracle database merge row records, wmsys WM_ Use of the concat function and group in MySQL_ Use and comparison of concat (ID).
核密度估计(二维、三维)
Katalon Studio Enterprise
2022 molten welding and thermal cutting work license and simulation examination
Common tools and commands for information collection
error:指针作为函数参数错误总结
[pytest learning] after the pytest case fails to execute, the others will not be executed
ASP. Net education OA system source code education industry OA system source code with document
美团获得小样本学习榜单FewCLUE第一!Prompt Learning+自训练实战
Tornado environment construction and basic framework construction -- familiar Hello World
满k叉树编号为 i 的节点的孩子编号公式推导
Learning C language from scratch day 039
微信小程序时间戳转化时间格式+时间相减
tornado环境搭建及基本框架搭建——熟悉的hello world
基于文本驱动用于创建和编辑图像(附源代码)