1、基础类型定义
const a: string = "1"; const b: number = 1; const c: Array<number> = [1]; const d: number[] = [1]; const f: any[] = [1, "1"]; // const g: Array<T> = [] as T; const h = <T>(a: T, b?: string, ...args: any[]): T => { return a;}; console.log(h(1, "1", a, b)); const g: boolean = true;const e: null = null; //元组let x: [string, number];//枚举enum Person { name, age, sex,} //默认从零开始enum Child { name = 1, age = 2, sex = 3,}console.log(Child[3]);const vb: object = {}; //表示所有的非原始类型const fv: Object = {}; //所有原始类型、非原始类型集合
2、interface定义 | type定义
interface A {
a: number;
b?: string; //可选
readonly c: []; //只读 只能在对象刚刚创建的时候修改其值
[propName: string]: any; //字符串索引签名
d: (...args: any[]) => void; // 函数类型声明
}
//引用数据类型
const o: A = { a: 1, b: "1", c: [], d: (args) => { }};
//断言
const p = { a: 1, b: "1", c: [],} as A;console.log(o.b);interface List { [x: number]: any; //数组可索引的类型}const list: List[] = [];console.log(list[0]);
// 使用方式不同type Name = string;interface Names { a: Document;}
3、Function定义
//柯里化函数 将函数参数复用const n = (a: any[]): Function => { return (b: number): boolean => { return a.includes(b); };};
//递归、尾递归const fn = (n: number): number | Function => { if (n > 10) { return n; } return fn(n + 1);};
//无返回函数定义const fg = (): void => { console.log('无返回函数定义');};
//两数之和 哈希表优化 差值是否在哈希表中const twoSum1 = (nums: number[], target: number) => { const map = new Map(); for (let i = 0; i < nums.length; i++) { let deff = target - nums[i]; if (map.has(deff)) { return [map.get(deff), i]; } else { map.set(nums[i], i); } } return [];};
4、class定义
class Test { public name: string; private sex: string; private age: number; constructor(name: string, sex: string, age: number) { this.name = name; this.sex = sex; this.age = age; } userInfo() { console.log(`${this.name}, ${this.sex}, ${this.age}`); } work() { console.log('9点开始工作...'); } paly() { console.log('play Genshin Impack'); }}class Son extends Test { constructor(name: string, sex: string, age: number) { super(name, sex, age) } getName() { return `${this.name}` } warp() { let str = '中南财经政法大学/n南湖校区文波楼' // str = str.length > 9 ? str.padStart(8, '111') : '' console.log(str); }}const panquan = new Test('cuteboy', 'boy', 18)const son = new Son('11', 'boy', 18)console.log(son.warp());