1. 数字、布尔、字符串
let num: number = 6;
let str: string = "6";
let bool: boolean = false;
2. 数组
// Array
let numArr1: number[] = [4, 3, 9, 9];
// 也可以利用泛型
let numArr2: Array = [7, 1, 3, 5];
3. 元组
【Typescript 学习笔记】元组可以进一步规范固定位置的类型,且长度不可变;
// tupple
let person1: [number, string] = [17, "aYao"]
4. Union 类型
// Union
let uni: string | number;
uni = 2;
uni = "2";
5. Enum 枚举
// Enum
enum Color {
red,
green,
blue
}
let color = Color.blue
console.log(color) // 2
6. any
let randomVal: any = 666;
randomVal = "777";
randomVal = {};
7. void、undefined和never
function printResult(): void {
console.log("lalala~");
}console.log(printResult()) // undefined
8. interface 与 class
interface IPoint {
x: number;
y: number;
drawPoint: () => void;
getDistances: (p: IPoint) => number;
}
// let drawPoint = (point: Point) => {
//console.log({ x: point.x, y: point.y });
// };
// drawPoint({ x: 4, y: 7 });
class Point implements IPoint {
x: number;
y: number;
// 构造函数constructor; ?: 表示可选参数,可以不给其赋值
constructor(x?: number, y?: number) {
this.x = x;
this.y = y;
}drawPoint = () => {
console.log("x:" + this.x + ",y:" + this.y);
};
getDistances = (p: IPoint) => {
return Math.pow(p.x - this.x, 2) + Math.pow(p.y - this.y, 2);
};
}const point = new Point(2, 3);
point.drawPoint();
// x:2,y:3
9. Generics
// 传入什么类型就返回什么类型
let lastInArr = (arr: Array) => {
return arr[arr.length - 1];
};
const l1 = lastInArr([1, 2, 3, 4]);
// string
const l2 = lastInArr(["1", "2", "3", "4"]);
// number
// 指定类型
const l3 = lastInArr(["1", "2", "3", "4"]);
// number | string
推荐阅读
- Webpack|一份不可多得的 Webpack 学习指南(共10k字)
- 开发工具|小马带你认识前端开发神器WebStorm(WebStorm及Git的相关配置与使用)
- Web 性能权威指南
- 前端工程师经常上哪些网站学习最新技术?
- 融合通信常见问题3月刊 | 云信小课堂
- xterm.js+react的综合使用(onKey以及onData的区别使用导致的光标串行问题)
- 衡石BI产品预置明道云数据连接器
- 前端实现多文件编译器
- 前端|VScode 主题和打字特效配置,让你的VScode活“”起来