当前位置:网站首页>Getting started with typescript
Getting started with typescript
2022-07-02 19:27:00 【zhuangwei_ eight thousand two hundred and fifty-six】
Typescript Quick start
Limit variable types
Basic data type
// Define basic data
let num: number = 3;
let str: string = 'aaa';
let bool: boolean = true;
let count = 2;
The basic data types will not be repeated , When a variable with a specified data type is assigned a value other than the data type, a type error will be prompted ;
Array
// Define an array
let arr: number[];
arr = [1, 2, 3]; // correct
arr = ['a', 2, 3]; // error
let arrOfArr: number[][]; // Define a two-dimensional array
arrOfArr = [
[1, 2, 3],
[4, 5, 6]
]
Tuples
It is very similar to the definition of array , Only tuples restrict element types , It also limits the number ;
// Define a tuple
let nums: [number, number, number];
nums = [1, 2, 3]; // It's very similar to arrays , Just limit the type and number of elements ;
// If you want one of them to omit the key , Just add a after the type ?, Then the data can have 3 individual , There can be 2 individual
let counts: [number, number, number?];
counts = [4, 5];
Joint type
// Joint type
// When you want a variable to be one of several arbitrary types :
let color:number | string; // color It can be either number , It can also be string
color = 'red';
color = 111111;
color = true; // Compiler error
// Use union types to implement enumeration
let gender: 'male' | 'female'
let n: 1 | 2 | 3 | 4;
gender = 'male'; // correct
gender = 'aaa'; // error
n = 3; // correct
n = 54; // error
Summary
need Be careful Yes. : For ordinary variables that are assigned initial values when defining variables , We don't really need to specify the type , Because the compiler can automatically do according to the initial value Type derivation , As in the code count.
Restrict the data type of the object
Use interface, If some fields are optional , Use when defining interfaces ? Just mark it .
interface User {
id: number;
name: string;
roles?: string[];
}
// If the object defined with this interface is missing or has more attributes , Compiler error
let userInfo: User = {
name: 'zhangsan',
age: 12, // Report errors
}
// If you want some fields of the object to be optional , You can use ? Mark this field , Such as roles Field ,userInfo2 There is a lack of roles Field , But the compiler does not report an error .
let userInfo2: User = {
// correct
id: 202206010001,
name: 'zhangsan',
}
Type the alias
- Type the alias : Use type keyword , The advantage of this definition is , If we use the same type elsewhere , You can reuse code directly by using aliases .
type Id = number | string;
function getName(id: Id) {
// ......
}
Function typescript
- Check the data type of function parameters :
function multiply(a: number, b: string) {
console.log(a, b)
}
multiply(1, 'a') // Parameters can only be passed in numbers 、 character string , And the two parameters must
multiply(1, 2) // Prompt parameters 2 Wrong type of
multiply('a', 'b') // Prompt parameters 1 Wrong type of
multiply(1) // Prompt missing parameters
and By default No, if the data type of the variable is not specified when defining the parameter , The default parameter is any type , In other words typescript This parameter will not be type checked ;
- You want a parameter of the function to be optional :
// Suppose you want to b Parameters are optional , Can pass but not pass , Just add a ? that will do
function multiply(a: number, b?: string) {
console.log(a, b)
}
multiply(1, 'a') // correct
multiply(1) // correct
- Check the data type of the return value of the function :
function multiply(a: number, b: number): number {
console.log(a, b)
return a + b;
}
let sumNum = multiply(1, 2);
// Or if a function has no return value , Designated as void The type is enough
function hello(): void {
alert('hello world!!!');
}
- Signature of function : The key point is that the function parameters are When calling back a function
function getName(callBack: (data: string) => void) {
// This method limits callBack The parameters of the callback function are string type , And no value is returned
}
// correct
getName((data) => {
alert(data);
})
// error
getName((data) => {
alert(data * 2);
})
If there is any deficiency , I hope you can give me some advice ! thank you !
边栏推荐
- Processing strategy of message queue message loss and repeated message sending
- The mybatieshelperpro tool can be generated to the corresponding project folder if necessary
- MySQL advanced learning summary 8: overview of InnoDB data storage structure page, internal structure of page, row format
- Transformation of thinking consciousness is the key to the success or failure of digital transformation of construction enterprises
- Horizontal ultra vires and vertical ultra vires [easy to understand]
- What is the MySQL backup suffix_ MySQL backup restore
- 冒泡排序数组
- metric_ Logger urination
- 高频面试题
- [论文阅读] CA-Net: Leveraging Contextual Features for Lung Cancer Prediction
猜你喜欢

PHP-Parser羽毛球预约小程序开发require线上系统
![[error record] problems related to the installation of the shuttle environment (follow-up error handling after executing the shuttle doctor command)](/img/c1/a00425f2e1824a50644c8fbb15fe38.jpg)
[error record] problems related to the installation of the shuttle environment (follow-up error handling after executing the shuttle doctor command)
冒泡排序数组

守望先锋世界观架构 ——(一款好的游戏是怎么来的)

数据降维——因子分析

What is 9D movie like? (+ common sense of dimension space)

Yunna | why use the fixed asset management system and how to enable it

高级性能测试系列《24. 通过jdbc执行sql脚本》

Hospital online inquiry source code hospital video inquiry source code hospital applet source code

PHP parser badminton reservation applet development requires online system
随机推荐
消息队列消息丢失和消息重复发送的处理策略
[论文阅读] CA-Net: Leveraging Contextual Features for Lung Cancer Prediction
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
[test development] takes you to know what software testing is
【ERP软件】ERP体系二次开发有哪些危险?
Codeworks 5 questions per day (1700 average) - day 4
GMapping代码解析[通俗易懂]
机器学习笔记 - 时间序列预测研究:法国香槟的月销量
Tutoriel (5.0) 10. Dépannage * fortiedr * fortinet Network Security expert NSE 5
教程篇(5.0) 09. RESTful API * FortiEDR * Fortinet 网络安全专家 NSE 5
Obligatoire pour les débutants, cliquez sur deux boutons pour passer à un contenu différent
PHP非对称加密方法私钥及公钥加密解密的方法
开发固定资产管理系统,开发固定资产管理系统用什么语音
mybatiesHelperPro工具必须的可以生成到对应项目文件夹下
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
MySQL advanced learning summary 7: MySQL data structure - Comparison of hash index, AVL tree, B tree and b+ tree
End-to-End Object Detection with Transformers(DETR)论文阅读与理解
SIFT feature point extraction "suggestions collection"
High frequency interview questions