个人学习笔记,供参考
// 定义数组的几种方式
let a: number[] = [1, 2, 3, NaN, Infinity];
let f: number[][] = [[1], [2], [3], [NaN], [Infinity]];
let b: Array<number> = [1, 2, 3];
let e: Array<Array<number>> = [[1], [2]];
let c: (string | number)[] = [1, "n"];
type Example = (number | string | void)[];
let d: Example = [1, "a", undefined];
// 接口和对象类型
interface A {
readonly name: string; //只读属性
age: number;
phone?: number;
cb?(): number;
[propName: string]: any; //使对象可添加任意属性,会限制该接口所有属性的类型
}
interface B extends A {
run: number;
}
interface C {
sex: string;
}
let obj: A = {
name: "hh",
age: 12,
phone: 12344,
eat: "水煮鱼",
cb: () => {
return 123;
},
};
let obj1: A = {
name: "hhs",
age: 12,
sing: true,
};
let obj2: B = {
name: "hhs",
age: 12,
run: 123,
};
// 类型别名
type Person = {
name: string;
age: number;
};
// 函数类型
// 定义函数参数、返回值类型
function fun(a: number, b: number = 10): number {
return a + b;
}
const add: (a: number, b: number) => number = (a, b) => {
return a + b;
}; // 只适用于函数表达式
// 如果函数没有返回值,则返回类型为void
function greet(name: string): void {
console.log("该函数没有返回值", name);
}
function fun1(user: A) {
console.log(user);
}
fun1(obj1); //{name: "hhs",age: 12,sing: true,}
// 交叉类型
function fun2(man: A & C): void {
console.log(man);
}
fun2({ ...obj1, sex: "男" }); //{name: "hhs",age: 12,sing: true, sex:'男'}
// 断言as
function fun3(num: A | C): void {
console.log((num as C).sex);
// console.log((<C>num).length);
}
fun3({ sex: "nv" }); //nv
fun3(obj1); //undefined
内置对象
html
<div class="test-div">HTMLDivElement</div>
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
ts
// ECMAscript的内置对象
const reg: RegExp = /\w\d\s/; // /\w\d\s/
const date: Date = new Date(); // 2022-11-29T09:27:28.133Z
const err: Error = new Error("错误");
let bool: Boolean = new Boolean(1); // [Boolean: true]
let n: Number = new Number(true); // [Number: 1]
let str: String = new String("字符串"); // [String: '字符串']
// DOM、BOM的内置对象
const list: NodeList = document.querySelectorAll(".list li");
const body: HTMLElement = document.body;
// console.dir()查看标签类型
const div = document.querySelector(".test-div") as HTMLDivElement;
document.addEventListener("click", (e: MouseEvent) => {
console.log(e);
});