当前位置:网站首页>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);
})
如有不足,望大家多多指点! 谢谢!
边栏推荐
猜你喜欢
[100 cases of JVM tuning practice] 02 - five cases of virtual machine stack and local method stack tuning
Watchful pioneer world outlook Architecture - (how does a good game come from)
新手必看,點擊兩個按鈕切換至不同的內容
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
教程篇(5.0) 10. 故障排除 * FortiEDR * Fortinet 网络安全专家 NSE 5
注解开发方式下AutowiredAnnotationBeanPostProcessor的注册时机
Hospital online inquiry source code hospital video inquiry source code hospital applet source code
juypter notebook 修改默认打开文件夹以及默认浏览器
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
使用 Cheat Engine 修改 Kingdom Rush 中的金钱、生命、星
随机推荐
Quanzhi A33 uses mainline u-boot
C file input operation
Use cheat engine to modify money, life and stars in Kingdom rush
"Patient's family, please come here" reading notes
2022 compilation principle final examination recall Edition
潇洒郎:彻底解决Markdown图片问题——无需上传图片——无需网络——转发给他人图片无缺失
【测试开发】软件测试—概念篇
Date tool class (updated from time to time)
[100 cases of JVM tuning practice] 01 - introduction of JVM and program counter
9D电影是怎样的?(+维度空间常识)
【ERP软件】ERP体系二次开发有哪些危险?
Novice must see, click two buttons to switch to different content
High frequency interview questions
Gstore weekly gstore source code analysis (4): black and white list configuration analysis of security mechanism
MySQL advanced learning summary 8: overview of InnoDB data storage structure page, internal structure of page, row format
MySQL advanced (Advanced) SQL statement
Markdown基础语法
[error record] problems related to the installation of the shuttle environment (follow-up error handling after executing the shuttle doctor command)
[0701] [paper reading] allowing data imbalance issue with perforated input during influence
#gStore-weekly | gStore源码解析(四):安全机制之黑白名单配置解析