当前位置:网站首页>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 !
边栏推荐
- Markdown基础语法
- When converting from list to map, if a certain attribute may cause key duplication and exceptions, you can set the way to deal with this duplication
- Reading notes of code neatness
- 股票证券公司排名,有安全保障吗
- Introduction of Ethernet PHY layer chip lan8720a
- Emmet基础语法
- #gStore-weekly | gStore源码解析(四):安全机制之黑白名单配置解析
- 教程篇(5.0) 10. 故障排除 * FortiEDR * Fortinet 網絡安全專家 NSE 5
- 论文导读 | 关于将预训练语言模型作为知识库的分析与批评
- Windows2008R2 安装 PHP7.4.30 必须 LocalSystem 启动应用程序池 不然500错误 FastCGI 进程意外退出
猜你喜欢

Data dimensionality reduction factor analysis

Why should we build an enterprise fixed asset management system and how can enterprises strengthen fixed asset management

Tutorial (5.0) 10 Troubleshooting * fortiedr * Fortinet network security expert NSE 5

High frequency interview questions

End to end object detection with transformers (Detr) paper reading and understanding

ICDE 2023|TKDE Poster Session(CFP)

Introduction to the paper | analysis and criticism of using the pre training language model as a knowledge base

IEDA refactor的用法

MySQL advanced learning summary 7: MySQL data structure - Comparison of hash index, AVL tree, B tree and b+ tree

Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
随机推荐
思维意识转变是施工企业数字化转型成败的关键
golang:[]byte转string
Refactoring: improving the design of existing code (Part 1)
A4988 drive stepper motor "recommended collection"
潇洒郎:彻底解决Markdown图片问题——无需上传图片——无需网络——转发给他人图片无缺失
QT中的QPropertyAnimation使用和toast案列
Codeworks 5 questions per day (1700 average) - day 4
IDEA编辑器去掉sql语句背景颜色SQL语句警告No data sources are configured to run this SQL...和SQL Dialect is Not Config
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
Learn the knowledge points of eight part essay ~ ~ 1
PHP非对称加密方法私钥及公钥加密解密的方法
mybatiesHelperPro工具必须的可以生成到对应项目文件夹下
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
C file input operation
Learning summary of MySQL advanced 6: concept and understanding of index, detailed explanation of b+ tree generation process, comparison between MyISAM and InnoDB
How performance testing creates business value
《重构:改善既有代码的设计》读书笔记(上)
[100 cases of JVM tuning practice] 01 - introduction of JVM and program counter
Golang:[]byte to string
2022.7.1-----leetcode.241