当前位置:网站首页>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 !
边栏推荐
- The mybatieshelperpro tool can be generated to the corresponding project folder if necessary
- C file input operation
- mysql备份后缀是什么_mysql备份还原
- Tutoriel (5.0) 10. Dépannage * fortiedr * fortinet Network Security expert NSE 5
- Golang:[]byte to string
- ORA-01455: converting column overflows integer datatype
- Golang concurrent programming goroutine, channel, sync
- Page title component
- Develop fixed asset management system, what voice is used to develop fixed asset management system
- Gmapping code analysis [easy to understand]
猜你喜欢
教程篇(5.0) 10. 故障排除 * FortiEDR * Fortinet 网络安全专家 NSE 5
论文导读 | 关于将预训练语言模型作为知识库的分析与批评
Data dimensionality reduction principal component analysis
xml开发方式下AutowiredAnnotationBeanPostProcessor的注册时机
Introduction to the paper | analysis and criticism of using the pre training language model as a knowledge base
[0701] [paper reading] allowing data imbalance issue with perforated input during influence
9D电影是怎样的?(+维度空间常识)
[test development] software testing - concept
Transformation of thinking consciousness is the key to the success or failure of digital transformation of construction enterprises
Refactoring: improving the design of existing code (Part 1)
随机推荐
What is the MySQL backup suffix_ MySQL backup restore
According to the atlas of data security products and services issued by the China Academy of information technology, meichuang technology has achieved full coverage of four major sectors
MySQL advanced (Advanced) SQL statement
PyTorch函数中的__call__和forward函数
Machine learning notes - time series prediction research: monthly sales of French champagne
A4988 drive stepper motor "recommended collection"
第七章-类基础
《代碼整潔之道》讀書筆記
Data dimensionality reduction principal component analysis
Mobile robot path planning: artificial potential field method [easy to understand]
【ERP软件】ERP体系二次开发有哪些危险?
冒泡排序数组
golang:[]byte转string
Preprocessing and preprocessing macros
[pytorch learning notes] tensor
二进制操作
Hospital online inquiry source code hospital video inquiry source code hospital applet source code
电脑使用哪个录制视频软件比较好
Windows2008R2 安装 PHP7.4.30 必须 LocalSystem 启动应用程序池 不然500错误 FastCGI 进程意外退出
[100 cases of JVM tuning practice] 02 - five cases of virtual machine stack and local method stack tuning