当前位置:网站首页>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 !
边栏推荐
- 虚拟机初始化脚本, 虚拟机相互免秘钥
- Qpropertyanimation use and toast case list in QT
- Learning summary of MySQL advanced 6: concept and understanding of index, detailed explanation of b+ tree generation process, comparison between MyISAM and InnoDB
- Date tool class (updated from time to time)
- 潇洒郎:彻底解决Markdown图片问题——无需上传图片——无需网络——转发给他人图片无缺失
- Emmet基础语法
- 横向越权与纵向越权[通俗易懂]
- 二进制操作
- Transformation of thinking consciousness is the key to the success or failure of digital transformation of construction enterprises
- PHP asymmetric encryption method private key and public key encryption and decryption method
猜你喜欢

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

PHP parser badminton reservation applet development requires online system

In pytorch function__ call__ And forward functions

Excel查找一列中的相同值,删除该行或替换为空值

Yunna | why use the fixed asset management system and how to enable it
![[0701] [paper reading] allowing data imbalance issue with perforated input during influence](/img/c7/9b7dc4b4bda4ecfe07aec1367fe059.png)
[0701] [paper reading] allowing data imbalance issue with perforated input during influence

数据降维——主成分分析

The difference between interceptor and filter

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

Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
随机推荐
【ERP软件】ERP体系二次开发有哪些危险?
高级性能测试系列《24. 通过jdbc执行sql脚本》
[0701] [论文阅读] Alleviating Data Imbalance Issue with Perturbed Input During Inference
Gstore weekly gstore source code analysis (4): black and white list configuration analysis of security mechanism
论文导读 | 机器学习在数据库基数估计中的应用
Golang并发编程——goroutine、channel、sync
[paper reading] Ca net: leveraging contextual features for lung cancer prediction
ORA-01455: converting column overflows integer datatype
Codeworks 5 questions per day (1700 average) - day 4
《代码整洁之道》读书笔记
Digital scroll strip animation
全志A33使用主线U-Boot
ICDE 2023|TKDE Poster Session(CFP)
End to end object detection with transformers (Detr) paper reading and understanding
PHP asymmetric encryption method private key and public key encryption and decryption method
Refactoring: improving the design of existing code (Part 1)
移动机器人路径规划:人工势场法[通俗易懂]
2022.7.1-----leetcode. two hundred and forty-one
新手必看,点击两个按钮切换至不同的内容
以太网PHY层芯片LAN8720A简介