当前位置:网站首页>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 !
边栏推荐
- Juypter notebook modify the default open folder and default browser
- Gamefi chain game system development (NFT chain game development function) NFT chain game system development (gamefi chain game development source code)
- 冒泡排序数组
- 使用CLion编译OGLPG-9th-Edition源码
- 2022.7.1-----leetcode.241
- PyTorch函数中的__call__和forward函数
- golang:[]byte转string
- [100 cases of JVM tuning practice] 01 - introduction of JVM and program counter
- [test development] takes you to know what software testing is
- 高级性能测试系列《24. 通过jdbc执行sql脚本》
猜你喜欢

Talk about the design of red envelope activities in e-commerce system

数据降维——因子分析

消息队列消息丢失和消息重复发送的处理策略

Markdown basic grammar

ICDE 2023|TKDE Poster Session(CFP)

开发固定资产管理系统,开发固定资产管理系统用什么语音
![[100 cases of JVM tuning practice] 01 - introduction of JVM and program counter](/img/c4/3bba96fda92328704c2ddd929dcdf6.png)
[100 cases of JVM tuning practice] 01 - introduction of JVM and program counter

Tutoriel (5.0) 10. Dépannage * fortiedr * fortinet Network Security expert NSE 5

教程篇(5.0) 09. RESTful API * FortiEDR * Fortinet 网络安全专家 NSE 5

IDEA编辑器去掉sql语句背景颜色SQL语句警告No data sources are configured to run this SQL...和SQL Dialect is Not Config
随机推荐
ORA-01455: converting column overflows integer datatype
Progress progress bar
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
预处理和预处理宏
In pytorch function__ call__ And forward functions
Data dimensionality reduction principal component analysis
Imitation Jingdong magnifying glass effect (pink teacher version)
Markdown basic grammar
Excel finds the same value in a column, deletes the row or replaces it with a blank value
How to print mybats log plug-in using XML file
Stm32g0 USB DFU upgrade verification error -2
守望先锋世界观架构 ——(一款好的游戏是怎么来的)
教程篇(5.0) 10. 故障排除 * FortiEDR * Fortinet 網絡安全專家 NSE 5
NPOI导出Excel2007
高频面试题
PHP asymmetric encryption method private key and public key encryption and decryption method
ORA-01455: converting column overflows integer datatype
Npoi export Excel2007
Reduce -- traverse element calculation. The specific calculation formula needs to be passed in and combined with BigDecimal
Introduction of Ethernet PHY layer chip lan8720a