@lppx/nlearn 1.1.12 → 1.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript 高级类型
4
+ * ==================
5
+ * 本文件介绍 TypeScript 的高级类型,包括:
6
+ * - 联合类型和交叉类型
7
+ * - 类型别名和接口
8
+ * - 字面量类型
9
+ * - 类型断言和类型守卫
10
+ *
11
+ * 适用版本:TypeScript 5.x
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.demonstrateUnionTypes = demonstrateUnionTypes;
15
+ exports.demonstrateIntersectionTypes = demonstrateIntersectionTypes;
16
+ exports.demonstrateLiteralTypes = demonstrateLiteralTypes;
17
+ exports.demonstrateTypeVsInterface = demonstrateTypeVsInterface;
18
+ exports.demonstrateTypeAssertion = demonstrateTypeAssertion;
19
+ exports.demonstrateTypeGuards = demonstrateTypeGuards;
20
+ // #region 示例1: 联合类型
21
+ function demonstrateUnionTypes() {
22
+ console.log('\n=== 联合类型示例 ===');
23
+ // 基本联合类型
24
+ let value;
25
+ value = 'hello';
26
+ console.log('字符串值:', value);
27
+ value = 42;
28
+ console.log('数字值:', value);
29
+ // 函数参数使用联合类型
30
+ function formatId(id) {
31
+ if (typeof id === 'string') {
32
+ return id.toUpperCase();
33
+ }
34
+ else {
35
+ return `ID-${id}`;
36
+ }
37
+ }
38
+ console.log('formatId("abc"):', formatId('abc'));
39
+ console.log('formatId(123):', formatId(123));
40
+ // 数组的联合类型
41
+ const mixed = [1, 'two', 3, 'four'];
42
+ console.log('混合数组:', mixed);
43
+ }
44
+ // #endregion
45
+ // #region 示例2: 交叉类型
46
+ function demonstrateIntersectionTypes() {
47
+ console.log('\n=== 交叉类型示例 ===');
48
+ const staff = {
49
+ name: 'Alice',
50
+ age: 30,
51
+ employeeId: 1001,
52
+ department: 'Engineering'
53
+ };
54
+ console.log('员工信息:', staff);
55
+ }
56
+ // #endregion
57
+ // #region 示例3: 字面量类型
58
+ function demonstrateLiteralTypes() {
59
+ console.log('\n=== 字面量类型示例 ===');
60
+ // 字符串字面量类型
61
+ let direction;
62
+ direction = 'up';
63
+ console.log('方向:', direction);
64
+ function rollDice() {
65
+ return (Math.floor(Math.random() * 6) + 1);
66
+ }
67
+ console.log('骰子点数:', rollDice());
68
+ function alwaysSucceed() {
69
+ return true;
70
+ }
71
+ console.log('总是成功:', alwaysSucceed());
72
+ function handleStatus(status) {
73
+ console.log('处理状态:', status);
74
+ }
75
+ handleStatus('pending');
76
+ handleStatus(404);
77
+ }
78
+ // #endregion
79
+ // #region 示例4: 类型别名 vs 接口
80
+ function demonstrateTypeVsInterface() {
81
+ console.log('\n=== 类型别名 vs 接口示例 ===');
82
+ const point = { x: 10, y: 20 };
83
+ console.log('Point (type):', point);
84
+ const rect = { width: 100, height: 50 };
85
+ console.log('Rectangle (interface):', rect);
86
+ const square = {
87
+ width: 50,
88
+ height: 50,
89
+ color: 'red'
90
+ };
91
+ console.log('Square (extends):', square);
92
+ function describeShape(shape) {
93
+ if ('x' in shape) {
94
+ console.log('这是一个点');
95
+ }
96
+ else if ('color' in shape) {
97
+ console.log('这是一个彩色方形');
98
+ }
99
+ else {
100
+ console.log('这是一个矩形');
101
+ }
102
+ }
103
+ console.log('\n形状描述:');
104
+ describeShape(point);
105
+ describeShape(square);
106
+ }
107
+ // #endregion
108
+ // #region 示例5: 类型断言
109
+ function demonstrateTypeAssertion() {
110
+ console.log('\n=== 类型断言示例 ===');
111
+ // as 语法
112
+ const someValue = 'this is a string';
113
+ const strLength = someValue.length;
114
+ console.log('字符串长度:', strLength);
115
+ // 尖括号语法(在 JSX 中不可用)
116
+ const anotherValue = 'hello';
117
+ const upperCase = anotherValue.toUpperCase();
118
+ console.log('大写:', upperCase);
119
+ // DOM 元素类型断言
120
+ // const input = document.getElementById('myInput') as HTMLInputElement;
121
+ // input.value = 'Hello';
122
+ // 非空断言(!)
123
+ function getLength(str) {
124
+ // 确信 str 不为 null
125
+ return str.length;
126
+ }
127
+ console.log('非空断言:', getLength('hello'));
128
+ // const 断言
129
+ const config = {
130
+ host: 'localhost',
131
+ port: 3000
132
+ };
133
+ // config.port = 4000; // 错误!所有属性都是只读的
134
+ console.log('只读配置:', config);
135
+ }
136
+ // #endregion
137
+ // #region 示例6: 类型守卫
138
+ function demonstrateTypeGuards() {
139
+ console.log('\n=== 类型守卫示例 ===');
140
+ // typeof 类型守卫
141
+ function processValue(value) {
142
+ if (typeof value === 'string') {
143
+ console.log('字符串长度:', value.length);
144
+ }
145
+ else {
146
+ console.log('数字平方:', value * value);
147
+ }
148
+ }
149
+ processValue('hello');
150
+ processValue(5);
151
+ // instanceof 类型守卫
152
+ class Dog {
153
+ bark() {
154
+ console.log('Woof!');
155
+ }
156
+ }
157
+ class Cat {
158
+ meow() {
159
+ console.log('Meow!');
160
+ }
161
+ }
162
+ function makeSound(animal) {
163
+ if (animal instanceof Dog) {
164
+ animal.bark();
165
+ }
166
+ else {
167
+ animal.meow();
168
+ }
169
+ }
170
+ console.log('\n动物叫声:');
171
+ makeSound(new Dog());
172
+ makeSound(new Cat());
173
+ function move(animal) {
174
+ if ('swim' in animal) {
175
+ console.log('游泳');
176
+ animal.swim();
177
+ }
178
+ else {
179
+ console.log('飞行');
180
+ animal.fly();
181
+ }
182
+ }
183
+ console.log('\n动物移动:');
184
+ move({ swim: () => console.log(' 鱼在游泳') });
185
+ move({ fly: () => console.log(' 鸟在飞翔') });
186
+ // 自定义类型守卫
187
+ function isString(value) {
188
+ return typeof value === 'string';
189
+ }
190
+ function processUnknown(value) {
191
+ if (isString(value)) {
192
+ console.log('处理字符串:', value.toUpperCase());
193
+ }
194
+ else {
195
+ console.log('不是字符串');
196
+ }
197
+ }
198
+ console.log('\n处理未知类型:');
199
+ processUnknown('hello');
200
+ processUnknown(123);
201
+ }
202
+ // #endregion
203
+ if (require.main === module) {
204
+ const examples = [
205
+ demonstrateUnionTypes,
206
+ demonstrateIntersectionTypes,
207
+ demonstrateLiteralTypes,
208
+ demonstrateTypeVsInterface,
209
+ demonstrateTypeAssertion,
210
+ demonstrateTypeGuards
211
+ ];
212
+ const exampleNumber = process.argv[2] ? parseInt(process.argv[2]) : 0;
213
+ if (exampleNumber > 0 && exampleNumber <= examples.length) {
214
+ examples[exampleNumber - 1]();
215
+ }
216
+ else {
217
+ console.log('运行所有示例...\n');
218
+ examples.forEach(example => example());
219
+ }
220
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript 泛型类型
4
+ * ==================
5
+ * 本文件介绍 TypeScript 的泛型,包括:
6
+ * - 泛型函数
7
+ * - 泛型接口和类
8
+ * - 泛型约束
9
+ * - 泛型工具类型
10
+ *
11
+ * 适用版本:TypeScript 5.x
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.demonstrateGenericFunctions = demonstrateGenericFunctions;
15
+ exports.demonstrateGenericInterfaces = demonstrateGenericInterfaces;
16
+ exports.demonstrateGenericClasses = demonstrateGenericClasses;
17
+ exports.demonstrateGenericConstraints = demonstrateGenericConstraints;
18
+ exports.demonstrateGenericUtilityTypes = demonstrateGenericUtilityTypes;
19
+ exports.demonstrateAdvancedGenericPatterns = demonstrateAdvancedGenericPatterns;
20
+ // #region 示例1: 泛型函数基础
21
+ function demonstrateGenericFunctions() {
22
+ console.log('\n=== 泛型函数基础示例 ===');
23
+ // 基本泛型函数
24
+ function identity(arg) {
25
+ return arg;
26
+ }
27
+ const num = identity(42);
28
+ console.log('identity<number>(42):', num);
29
+ const str = identity('hello');
30
+ console.log('identity<string>("hello"):', str);
31
+ // 类型推断
32
+ const inferred = identity('world'); // TypeScript 自动推断为 string
33
+ console.log('identity("world"):', inferred);
34
+ // 泛型数组函数
35
+ function getFirst(arr) {
36
+ return arr[0];
37
+ }
38
+ console.log('getFirst([1, 2, 3]):', getFirst([1, 2, 3]));
39
+ console.log('getFirst(["a", "b"]):', getFirst(['a', 'b']));
40
+ }
41
+ // #endregion
42
+ // #region 示例2: 泛型接口
43
+ function demonstrateGenericInterfaces() {
44
+ console.log('\n=== 泛型接口示例 ===');
45
+ const numberBox = { value: 42 };
46
+ console.log('Number Box:', numberBox);
47
+ const stringBox = { value: 'hello' };
48
+ console.log('String Box:', stringBox);
49
+ const myIdentity = (x) => x;
50
+ console.log('myIdentity(10):', myIdentity(10));
51
+ const pair = {
52
+ key: 'age',
53
+ value: 25
54
+ };
55
+ console.log('Pair:', pair);
56
+ }
57
+ // #endregion
58
+ // #region 示例3: 泛型类
59
+ function demonstrateGenericClasses() {
60
+ console.log('\n=== 泛型类示例 ===');
61
+ // 泛型类
62
+ class Stack {
63
+ constructor() {
64
+ this.items = [];
65
+ }
66
+ push(item) {
67
+ this.items.push(item);
68
+ }
69
+ pop() {
70
+ return this.items.pop();
71
+ }
72
+ peek() {
73
+ return this.items[this.items.length - 1];
74
+ }
75
+ size() {
76
+ return this.items.length;
77
+ }
78
+ }
79
+ const numberStack = new Stack();
80
+ numberStack.push(1);
81
+ numberStack.push(2);
82
+ numberStack.push(3);
83
+ console.log('Number Stack size:', numberStack.size());
84
+ console.log('Pop:', numberStack.pop());
85
+ console.log('Peek:', numberStack.peek());
86
+ const stringStack = new Stack();
87
+ stringStack.push('a');
88
+ stringStack.push('b');
89
+ console.log('\nString Stack size:', stringStack.size());
90
+ console.log('Pop:', stringStack.pop());
91
+ }
92
+ // #endregion
93
+ // #region 示例4: 泛型约束
94
+ function demonstrateGenericConstraints() {
95
+ console.log('\n=== 泛型约束示例 ===');
96
+ function logLength(arg) {
97
+ console.log('Length:', arg.length);
98
+ }
99
+ logLength('hello'); // string 有 length
100
+ logLength([1, 2, 3]); // array 有 length
101
+ logLength({ length: 10, value: 'test' }); // 对象有 length
102
+ // logLength(123); // 错误!number 没有 length
103
+ // 使用类型参数约束
104
+ function getProperty(obj, key) {
105
+ return obj[key];
106
+ }
107
+ const person = { name: 'Alice', age: 25 };
108
+ console.log('\ngetProperty(person, "name"):', getProperty(person, 'name'));
109
+ console.log('getProperty(person, "age"):', getProperty(person, 'age'));
110
+ // getProperty(person, 'email'); // 错误!email 不是 person 的属性
111
+ }
112
+ // #endregion
113
+ // #region 示例5: 泛型工具类型
114
+ function demonstrateGenericUtilityTypes() {
115
+ console.log('\n=== 泛型工具类型示例 ===');
116
+ const preview = { id: 1, name: 'Alice' };
117
+ console.log('Pick:', preview);
118
+ const userNoEmail = { id: 2, name: 'Bob', age: 30 };
119
+ console.log('Omit:', userNoEmail);
120
+ const partialUser = { name: 'Charlie' };
121
+ console.log('Partial:', partialUser);
122
+ const requiredUser = { id: 3, name: 'David' };
123
+ console.log('Required:', requiredUser);
124
+ const readonlyUser = {
125
+ id: 4,
126
+ name: 'Eve',
127
+ email: 'eve@example.com',
128
+ age: 28
129
+ };
130
+ console.log('Readonly:', readonlyUser);
131
+ // readonlyUser.name = 'Frank'; // 错误!
132
+ }
133
+ // #endregion
134
+ // #region 示例6: 高级泛型模式
135
+ function demonstrateAdvancedGenericPatterns() {
136
+ console.log('\n=== 高级泛型模式示例 ===');
137
+ console.log('条件类型已定义');
138
+ const nullableUser = {
139
+ name: 'Alice',
140
+ age: null
141
+ };
142
+ console.log('Nullable User:', nullableUser);
143
+ const deepReadonly = {
144
+ a: {
145
+ b: {
146
+ c: 42
147
+ }
148
+ }
149
+ };
150
+ console.log('Deep Readonly:', deepReadonly);
151
+ const defaultContainer = { value: 'default' };
152
+ const numberContainer = { value: 42 };
153
+ console.log('Default Container:', defaultContainer);
154
+ console.log('Number Container:', numberContainer);
155
+ }
156
+ // #endregion
157
+ if (require.main === module) {
158
+ const examples = [
159
+ demonstrateGenericFunctions,
160
+ demonstrateGenericInterfaces,
161
+ demonstrateGenericClasses,
162
+ demonstrateGenericConstraints,
163
+ demonstrateGenericUtilityTypes,
164
+ demonstrateAdvancedGenericPatterns
165
+ ];
166
+ const exampleNumber = process.argv[2] ? parseInt(process.argv[2]) : 0;
167
+ if (exampleNumber > 0 && exampleNumber <= examples.length) {
168
+ examples[exampleNumber - 1]();
169
+ }
170
+ else {
171
+ console.log('运行所有示例...\n');
172
+ examples.forEach(example => example());
173
+ }
174
+ }
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript 基础运算符
4
+ * =====================
5
+ * 涵盖算术运算符、赋值运算符、比较运算符和逻辑运算符
6
+ * 适用于 TypeScript 5.x
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.arithmeticOperators = arithmeticOperators;
10
+ exports.assignmentOperators = assignmentOperators;
11
+ exports.comparisonOperators = comparisonOperators;
12
+ exports.logicalOperators = logicalOperators;
13
+ exports.stringOperators = stringOperators;
14
+ // #region 示例1: 算术运算符
15
+ function arithmeticOperators() {
16
+ console.log('=== 算术运算符 ===');
17
+ const a = 10;
18
+ const b = 3;
19
+ console.log(`加法: ${a} + ${b} = ${a + b}`);
20
+ console.log(`减法: ${a} - ${b} = ${a - b}`);
21
+ console.log(`乘法: ${a} * ${b} = ${a * b}`);
22
+ console.log(`除法: ${a} / ${b} = ${a / b}`);
23
+ console.log(`取余: ${a} % ${b} = ${a % b}`);
24
+ console.log(`幂运算: ${a} ** ${b} = ${a ** b}`);
25
+ // 自增自减
26
+ let count = 5;
27
+ console.log(`\n原始值: ${count}`);
28
+ console.log(`后置自增 count++: ${count++}`); // 先返回再加
29
+ console.log(`自增后的值: ${count}`);
30
+ console.log(`前置自增 ++count: ${++count}`); // 先加再返回
31
+ console.log(`后置自减 count--: ${count--}`);
32
+ console.log(`前置自减 --count: ${--count}`);
33
+ }
34
+ // #endregion
35
+ // #region 示例2: 赋值运算符
36
+ function assignmentOperators() {
37
+ console.log('\n=== 赋值运算符 ===');
38
+ let x = 10;
39
+ console.log(`初始值: x = ${x}`);
40
+ x += 5; // x = x + 5
41
+ console.log(`x += 5: ${x}`);
42
+ x -= 3; // x = x - 3
43
+ console.log(`x -= 3: ${x}`);
44
+ x *= 2; // x = x * 2
45
+ console.log(`x *= 2: ${x}`);
46
+ x /= 4; // x = x / 4
47
+ console.log(`x /= 4: ${x}`);
48
+ x %= 5; // x = x % 5
49
+ console.log(`x %= 5: ${x}`);
50
+ x **= 3; // x = x ** 3
51
+ console.log(`x **= 3: ${x}`);
52
+ }
53
+ // #endregion
54
+ // #region 示例3: 比较运算符
55
+ function comparisonOperators() {
56
+ console.log('\n=== 比较运算符 ===');
57
+ const num1 = 10;
58
+ const num2 = '10'; // 使用 any 来演示类型转换
59
+ const num3 = 20;
60
+ // 相等性比较
61
+ console.log(`${num1} == '${num2}': ${num1 == num2}`); // 宽松相等(类型转换)
62
+ console.log(`${num1} === '${num2}': ${num1 === num2}`); // 严格相等(不转换类型)
63
+ console.log(`${num1} != '${num2}': ${num1 != num2}`);
64
+ console.log(`${num1} !== '${num2}': ${num1 !== num2}`);
65
+ // 大小比较
66
+ console.log(`\n${num1} > ${num3}: ${num1 > num3}`);
67
+ console.log(`${num1} < ${num3}: ${num1 < num3}`);
68
+ console.log(`${num1} >= ${num1}: ${num1 >= num1}`);
69
+ console.log(`${num1} <= ${num3}: ${num1 <= num3}`);
70
+ }
71
+ // #endregion
72
+ // #region 示例4: 逻辑运算符
73
+ function logicalOperators() {
74
+ console.log('\n=== 逻辑运算符 ===');
75
+ const isAdult = true;
76
+ const hasLicense = false;
77
+ const age = 25;
78
+ // 逻辑与 (AND)
79
+ console.log(`isAdult && hasLicense: ${isAdult && hasLicense}`);
80
+ console.log(`可以开车: ${isAdult && hasLicense}`);
81
+ // 逻辑或 (OR)
82
+ console.log(`\nisAdult || hasLicense: ${isAdult || hasLicense}`);
83
+ console.log(`至少满足一个条件: ${isAdult || hasLicense}`);
84
+ // 逻辑非 (NOT)
85
+ console.log(`\n!isAdult: ${!isAdult}`);
86
+ console.log(`!hasLicense: ${!hasLicense}`);
87
+ // 组合使用
88
+ const canDrive = isAdult && hasLicense;
89
+ const needsPermission = !isAdult || !hasLicense;
90
+ console.log(`\n可以开车: ${canDrive}`);
91
+ console.log(`需要许可: ${needsPermission}`);
92
+ // 短路求值
93
+ console.log('\n短路求值示例:');
94
+ const result1 = false && console.log('这不会执行');
95
+ const result2 = true || console.log('这也不会执行');
96
+ console.log('短路求值完成');
97
+ }
98
+ // #endregion
99
+ // #region 示例5: 字符串运算符
100
+ function stringOperators() {
101
+ console.log('\n=== 字符串运算符 ===');
102
+ const firstName = 'Zhang';
103
+ const lastName = 'San';
104
+ // 字符串连接
105
+ const fullName = firstName + ' ' + lastName;
106
+ console.log(`全名: ${fullName}`);
107
+ // 使用 += 连接
108
+ let message = 'Hello';
109
+ message += ', ';
110
+ message += 'World!';
111
+ console.log(`消息: ${message}`);
112
+ // 模板字符串(推荐方式)
113
+ const greeting = `你好, ${firstName} ${lastName}!`;
114
+ console.log(greeting);
115
+ // 字符串与数字
116
+ const str = '100'; // 使用 any 来演示类型转换
117
+ const num = 50;
118
+ console.log(`\n字符串 + 数字: '${str}' + ${num} = ${str + num}`); // 字符串连接
119
+ console.log(`字符串 - 数字: '${str}' - ${num} = ${str - num}`); // 数字运算(自动转换)
120
+ }
121
+ // #endregion
122
+ if (require.main === module) {
123
+ const examples = [
124
+ arithmeticOperators,
125
+ assignmentOperators,
126
+ comparisonOperators,
127
+ logicalOperators,
128
+ stringOperators
129
+ ];
130
+ const exampleNumber = parseInt(process.argv[2]);
131
+ if (exampleNumber && exampleNumber > 0 && exampleNumber <= examples.length) {
132
+ console.log(`\n运行示例 ${exampleNumber}:\n`);
133
+ examples[exampleNumber - 1]();
134
+ }
135
+ else {
136
+ console.log('运行所有示例:\n');
137
+ examples.forEach((example, index) => {
138
+ console.log(`\n${'='.repeat(50)}`);
139
+ console.log(`示例 ${index + 1}`);
140
+ console.log('='.repeat(50));
141
+ example();
142
+ });
143
+ }
144
+ }