当前位置:网站首页>Typescript 之 快速入门
Typescript 之 快速入门
2022-07-02 18:20:00 【zhuangwei_8256】
限制变量类型
基本数据类型
// 定义基本数据
let num: number = 3;
let str: string = 'aaa';
let bool: boolean = true;
let count = 2;
基本数据类型就不多赘述了,当给指定了数据类型的变量赋值了非该数据类型的值时就会提示类型错误;
数组
// 定义数组
let arr: number[];
arr = [1, 2, 3]; // 正确
arr = ['a', 2, 3]; // 错误
let arrOfArr: number[][]; // 定义一个二维数组
arrOfArr = [
[1, 2, 3],
[4, 5, 6]
]
元组
和数组的定义很类似,只是元组既限制了元素类型,也限制了个数;
// 定义一个元组
let nums: [number, number, number];
nums = [1, 2, 3]; // 和数组很类似,只是限制元素类型以及个数;
// 如果希望其中一个可以省略调的话,只需要在类型后面加个?,那么该数据就既可以有3个,也可以有2个
let counts: [number, number, number?];
counts = [4, 5];
联合类型
// 联合类型
// 当希望某个变量是多个任意类型中的其中一种时:
let color:number | string; // color 既可以是number ,也可以是 string
color = 'red';
color = 111111;
color = true; // 编译器报错
// 利用联合类型实现枚举
let gender: 'male' | 'female'
let n: 1 | 2 | 3 | 4;
gender = 'male'; // 正确
gender = 'aaa'; // 错误
n = 3; // 正确
n = 54; // 错误
小结
需要 注意 的是:对在定义变量时就赋了初始值的普通变量,我们其实不需要明确指定类型,因为编译器能够自动根据初始值做类型推导,如代码中的 count。
限制对象的数据类型
使用 interface,某些字段如果是可选的,定义接口的时候使用 ? 标记即可。
interface User {
id: number;
name: string;
roles?: string[];
}
// 如果使用该接口定义的对象缺少或者多出了某些属性,编译器报错
let userInfo: User = {
name: 'zhangsan',
age: 12, // 报错
}
// 如果希望对象的某些字段是可选的,可用? 标记该字段,如roles字段,userInfo2中是缺少roles字段的,但是编译器并不会报错。
let userInfo2: User = {
// 正确
id: 202206010001,
name: 'zhangsan',
}
类型别名
- 类型别名: 使用 type关键字,这样定义的好处是,如果我们在其他地方使用到了相同类型,可以直接使用别名来进行代码的复用。
type Id = number | string;
function getName(id: Id) {
// ......
}
函数中的typescript
- 对函数参数进行数据类型检查:
function multiply(a: number, b: string) {
console.log(a, b)
}
multiply(1, 'a') // 参数分别只能传入数字、字符串,且两个参数必须
multiply(1, 2) // 提示参数2的类型错误
multiply('a', 'b') // 提示参数1的类型错误
multiply(1) // 提示漏传参
而默认情况下没有如果在定义参数的时候没有指定变量的数据类型时,那么默认该参数是 any 类型,换句话说就是 typescript 不会对该参数进行类型检查;
- 希望函数的某个参数是可选的:
// 假设希望 b 参数是可选的,可传可不传,只需要在该参数后面加一个?即可
function multiply(a: number, b?: string) {
console.log(a, b)
}
multiply(1, 'a') // 正确
multiply(1) // 正确
- 对函数的返回值进行数据类型检查:
function multiply(a: number, b: number): number {
console.log(a, b)
return a + b;
}
let sumNum = multiply(1, 2);
// 或者如果一个函数没有返回值,指定为 void类型即可
function hello(): void {
alert('hello world!!!');
}
- 函数的签名:重点体现在函数参数为 回调函数时
function getName(callBack: (data: string) => void) {
// 该方法限制了callBack 回调函数的参数为 string 类型,并且没有返回值
}
// 正确
getName((data) => {
alert(data);
})
// 错误
getName((data) => {
alert(data * 2);
})
如有不足,望大家多多指点! 谢谢!
边栏推荐
- 电脑使用哪个录制视频软件比较好
- 新手必看,點擊兩個按鈕切換至不同的內容
- R language dplyr package filter function filters dataframe data. If the name of the data column (variable) to be filtered contains quotation marks, you need to use!! SYM syntax processing, otherwise n
- 全志A33使用主线U-Boot
- Kubernetes three open interfaces first sight
- Yolov3 trains its own data set to generate train txt
- 2022编译原理期末考试 回忆版
- 高频面试题
- Introduction to the paper | analysis and criticism of using the pre training language model as a knowledge base
- 消息队列消息丢失和消息重复发送的处理策略
猜你喜欢

Stm32g0 USB DFU upgrade verification error -2

How performance testing creates business value
![[论文阅读] CA-Net: Leveraging Contextual Features for Lung Cancer Prediction](/img/ef/bb48ee88d5dc6fe876a498ab53106e.png)
[论文阅读] CA-Net: Leveraging Contextual Features for Lung Cancer Prediction

机器学习笔记 - 时间序列预测研究:法国香槟的月销量

Transformation of thinking consciousness is the key to the success or failure of digital transformation of construction enterprises
![[100 cases of JVM tuning practice] 02 - five cases of virtual machine stack and local method stack tuning](/img/59/6c776e0607a52962b72fbea2e64c8e.png)
[100 cases of JVM tuning practice] 02 - five cases of virtual machine stack and local method stack tuning

Imitation Jingdong magnifying glass effect (pink teacher version)

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

In pytorch function__ call__ And forward functions

What is 9D movie like? (+ common sense of dimension space)
随机推荐
Date tool class (updated from time to time)
yolov3 训练自己的数据集之生成train.txt
性能测试如何创造业务价值
2022.7.1-----leetcode. two hundred and forty-one
[test development] takes you to know what software testing is
Progress progress bar
PyTorch函数中的__call__和forward函数
Tutorial (5.0) 09 Restful API * fortiedr * Fortinet network security expert NSE 5
Chic Lang: completely solve the problem of markdown pictures - no need to upload pictures - no need to network - there is no lack of pictures forwarded to others
"Patient's family, please come here" reading notes
End to end object detection with transformers (Detr) paper reading and understanding
Page title component
Virtual machine initialization script, virtual machine mutual secret key free
[100 cases of JVM tuning practice] 03 -- four cases of JVM heap tuning
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
为什么要做企业固定资产管理系统,企业如何加强固定资产管理
开发固定资产管理系统,开发固定资产管理系统用什么语音
Juypter notebook modify the default open folder and default browser
[test development] software testing - concept
2022 compilation principle final examination recall Edition