当前位置: 首页 > news >正文

JavaScript系列(17)--类型系统模拟

JavaScript类型系统模拟 🎭

今天,让我们深入探讨JavaScript中的类型系统模拟。虽然JavaScript是一门动态类型语言,但我们可以通过各种方式来实现类型检查和验证。

类型系统基础 🌟

💡 小知识:JavaScript是一门动态类型语言,但我们可以通过运行时类型检查、TypeScript等工具,或自定义类型系统来增强类型安全性。

基本类型检查 📊

// 1. 类型检查工具
class TypeChecker {static checkType(value, expectedType) {const actualType = typeof value;if (actualType !== expectedType) {throw new TypeError(`Expected type ${expectedType}, but got ${actualType}`);}return value;}static isNumber(value) {return typeof value === 'number' && !isNaN(value);}static isString(value) {return typeof value === 'string';}static isBoolean(value) {return typeof value === 'boolean';}static isFunction(value) {return typeof value === 'function';}static isObject(value) {return value !== null && typeof value === 'object';}static isArray(value) {return Array.isArray(value);}static isInstanceOf(value, constructor) {return value instanceof constructor;}
}// 2. 类型断言
function typeAssertions() {function assertNumber(value, message = 'Value must be a number') {if (!TypeChecker.isNumber(value)) {throw new TypeError(message);}return value;}function assertString(value, message = 'Value must be a string') {if (!TypeChecker.isString(value)) {throw new TypeError(message);}return value;}function assertNonNull(value, message = 'Value cannot be null or undefined') {if (value === null || value === undefined) {throw new TypeError(message);}return value;}// 使用示例function calculateArea(width, height) {assertNumber(width, 'Width must be a number');assertNumber(height, 'Height must be a number');return width * height;}
}// 3. 类型守卫
function typeGuards() {// 类型守卫函数function isString(value): value is string {return typeof value === 'string';}function isNumber(value): value is number {return typeof value === 'number' && !isNaN(value);}function isArray(value): value is Array<any> {return Array.isArray(value);}// 使用示例function processValue(value: any) {if (isString(value)) {return value.toUpperCase();} else if (isNumber(value)) {return value.toFixed(2);} else if (isArray(value)) {return value.length;}throw new TypeError('Unsupported type');}
}

高级类型系统实现 🔧

// 1. 泛型类型实现
class GenericType<T> {private value: T;constructor(value: T) {this.value = value;}getValue(): T {return this.value;}map<U>(fn: (value: T) => U): GenericType<U> {return new GenericType(fn(this.value));}
}// 2. 联合类型实现
class UnionType {private value: any;private types: Function[];constructor(value: any, ...types: Function[]) {if (!types.some(type => this.checkType(value, type))) {throw new TypeError('Value does not match any of the specified types');}this.value = value;this.types = types;}private checkType(value: any, type: Function): boolean {if (type === String) return typeof value === 'string';if (type === Number) return typeof value === 'number';if (type === Boolean) return typeof value === 'boolean';return value instanceof type;}getValue(): any {return this.value;}
}// 3. 交叉类型实现
class IntersectionType {private value: any;constructor(value: any, ...types: Function[]) {if (!types.every(type => this.checkType(value, type))) {throw new TypeError('Value does not match all specified types');}this.value = value;}private checkType(value: any, type: Function): boolean {return Object.getOwnPropertyNames(type.prototype).every(prop => typeof value[prop] === typeof type.prototype[prop]);}getValue(): any {return this.value;}
}

类型系统应用 💼

让我们看看类型系统在实际开发中的应用:

// 1. 验证器系统
class Validator {private rules: Map<string, Function[]>;constructor() {this.rules = new Map();}// 添加验证规则addRule(field: string, ...validators: Function[]) {if (!this.rules.has(field)) {this.rules.set(field, []);}this.rules.get(field)!.push(...validators);}// 验证对象validate(obj: any): ValidationResult {const errors = new Map();for (const [field, validators] of this.rules) {const value = obj[field];const fieldErrors = validators.map(validator => validator(value)).filter(error => error !== null);if (fieldErrors.length > 0) {errors.set(field, fieldErrors);}}return {isValid: errors.size === 0,errors};}// 预定义验证器static required(value: any) {return value === undefined || value === null || value === '' ? 'Field is required' : null;}static minLength(length: number) {return (value: string) => value.length < length ? `Minimum length is ${length}` : null;}static maxLength(length: number) {return (value: string) => value.length > length ? `Maximum length is ${length}` : null;}static pattern(regex: RegExp, message: string) {return (value: string) => !regex.test(value) ? message : null;}
}// 2. 类型安全的事件系统
class TypedEventEmitter<Events extends Record<string, any>> {private listeners: Map<keyof Events, Function[]>;constructor() {this.listeners = new Map();}on<K extends keyof Events>(event: K, listener: (data: Events[K]) => void) {if (!this.listeners.has(event)) {this.listeners.set(event, []);}this.listeners.get(event)!.push(listener);return () => this.off(event, listener);}off<K extends keyof Events>(event: K, listener: (data: Events[K]) => void) {const listeners = this.listeners.get(event);if (listeners) {const index = listeners.indexOf(listener);if (index !== -1) {listeners.splice(index, 1);}}}emit<K extends keyof Events>(event: K, data: Events[K]) {const listeners = this.listeners.get(event);if (listeners) {listeners.forEach(listener => listener(data));}}
}// 3. 类型安全的状态管理
class TypedStore<State extends object> {private state: State;private listeners: Set<(state: State) => void>;constructor(initialState: State) {this.state = initialState;this.listeners = new Set();}getState(): Readonly<State> {return Object.freeze({ ...this.state });}setState(partial: Partial<State>) {this.state = { ...this.state, ...partial };this.notify();}subscribe(listener: (state: State) => void) {this.listeners.add(listener);return () => this.listeners.delete(listener);}private notify() {const state = this.getState();this.listeners.forEach(listener => listener(state));}
}

性能优化 ⚡

类型检查和验证的性能优化技巧:

// 1. 缓存类型检查结果
class TypeCache {private static cache = new WeakMap<object, Map<string, boolean>>();static checkType(obj: object, type: string): boolean {let typeCache = this.cache.get(obj);if (!typeCache) {typeCache = new Map();this.cache.set(obj, typeCache);}if (typeCache.has(type)) {return typeCache.get(type)!;}const result = this.performTypeCheck(obj, type);typeCache.set(type, result);return result;}private static performTypeCheck(obj: object, type: string): boolean {// 实际的类型检查逻辑return typeof obj === type;}
}// 2. 批量类型检查优化
class BatchTypeChecker {private validations: Array<() => boolean>;constructor() {this.validations = [];}addValidation(validation: () => boolean) {this.validations.push(validation);}validate(): boolean {// 使用 Array.every 进行短路优化return this.validations.every(validation => validation());}
}// 3. 延迟类型检查
class LazyTypeChecker {private typeChecks: Map<string, () => boolean>;private results: Map<string, boolean>;constructor() {this.typeChecks = new Map();this.results = new Map();}addCheck(name: string, check: () => boolean) {this.typeChecks.set(name, check);}check(name: string): boolean {if (!this.results.has(name)) {const check = this.typeChecks.get(name);if (!check) return false;this.results.set(name, check());}return this.results.get(name)!;}
}

最佳实践建议 💡

  1. 类型检查策略
// 1. 运行时类型检查
function runtimeTypeChecking() {// 基本类型检查function checkPrimitive(value: any, type: string) {return typeof value === type;}// 复杂类型检查function checkComplex(value: any, type: Function) {return value instanceof type;}// 结构类型检查function checkStructure(value: any, structure: object) {return Object.entries(structure).every(([key, type]) => {return checkPrimitive(value[key], type as string);});}
}// 2. 类型安全的API设计
function typeSecureAPI() {interface APIOptions {endpoint: string;method: 'GET' | 'POST' | 'PUT' | 'DELETE';headers?: Record<string, string>;body?: any;}class APIClient {request<T>(options: APIOptions): Promise<T> {// 实现类型安全的API请求return fetch(options.endpoint, {method: options.method,headers: options.headers,body: JSON.stringify(options.body)}).then(res => res.json());}}
}// 3. 类型转换安全
function typeConversionSafety() {// 安全的数字转换function toNumber(value: any): number {if (typeof value === 'number') return value;if (typeof value === 'string') {const num = Number(value);if (!isNaN(num)) return num;}throw new TypeError('Cannot convert to number');}// 安全的布尔转换function toBoolean(value: any): boolean {if (typeof value === 'boolean') return value;if (typeof value === 'string') {return ['true', '1', 'yes'].includes(value.toLowerCase());}return Boolean(value);}
}

结语 📝

JavaScript的类型系统虽然是动态的,但通过合适的工具和技术,我们可以实现强大的类型检查和验证。我们学习了:

  1. 基本的类型检查方法
  2. 高级类型系统的实现
  3. 实际应用场景
  4. 性能优化技巧
  5. 最佳实践和注意事项

💡 学习建议:在使用类型系统时,要平衡类型安全性和开发效率。可以考虑使用TypeScript等工具来获得更好的类型支持,同时在运行时实现必要的类型检查。


如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇

终身学习,共同成长。

咱们下一期见

💻

相关文章:

JavaScript系列(17)--类型系统模拟

JavaScript类型系统模拟 &#x1f3ad; 今天&#xff0c;让我们深入探讨JavaScript中的类型系统模拟。虽然JavaScript是一门动态类型语言&#xff0c;但我们可以通过各种方式来实现类型检查和验证。 类型系统基础 &#x1f31f; &#x1f4a1; 小知识&#xff1a;JavaScript是…...

openssl编译

关于windows下&#xff0c;openssl编译 环境准备 安装 perl:https://djvniu.jb51.net/200906/tools/ActivePerl5_64.rar安装nasm&#xff1a;https://www.nasm.us/pub/nasm/releasebuilds/2.13.01/win64/nasm-2.13.01-installer-x64.exe下载opensll源码&#xff1a;https://o…...

校园网络综合布线系统设计与实践

校园网络综合布线系统设计与实践 摘要&#xff1a;随着信息时代的发展&#xff0c;网络综合布线显得更加重要。综合布线技术也日益引起人的重视。综合布线管理系统是一个实用性十分强的系统工程&#xff0c;同样又是现代社区信息化建设的基础与必要产品&#xff0c;是对多用途…...

如果商品信息更新,爬虫会失效吗?

当商品信息更新时&#xff0c;爬虫是否失效取决于更新的具体内容。以下是一些可能影响爬虫的因素&#xff1a; 可能导致爬虫失效的情况 HTML结构变化&#xff1a;如果 yiwugo 平台更新了商品详情页面的 HTML 结构&#xff0c;比如改变了元素的标签、类名或 ID&#xff0c;那么…...

【UE5 C++课程系列笔记】27——多线程基础——ControlFlow插件的基本使用

目录 步骤 一、搭建基本同步框架 二、添加委托 三、添加蓝图互动框架 四、修改为异步框架 完整代码 通过一个游戏初始化流程的示例来介绍“ControlFlows”的基本使用。 步骤 一、搭建基本同步框架 1. 勾选“ControlFlows”插件 2. 新建一个空白C类&#xff0c;这里…...

有收到腾讯委托律师事务所向AppStore投诉带有【水印相机】主标题名称App的开发者吗

近期&#xff0c;有多名开发者反馈&#xff0c;收到来自腾讯科技 (深圳) 有限公司委托北京的一家**诚律师事务所卞&#xff0c;写给AppStore的投诉邮件。 邮件内容主要说的是&#xff0c;腾讯注册了【水印相机】这四个字的商标&#xff0c;所以你们这些在AppStore上的app&…...

标定 3

标定场景与对应的方式 标定板标定主要应用场景: (1)无法获取到执行机构物理坐标值,比如相机固定,执行机构为传送带等 (2)相机存在畸变等非线性标定情况,需要进行畸变校正 (3)标定单像素精度 (4)获取两个相机之间的坐标系关系 标定板操作步骤: (1)确定好拍…...

用 C# 绘制谢尔宾斯基垫片

谢尔宾斯基垫片是一个三角形&#xff0c;分解成多个小三角形&#xff0c;如右图所示。有几种方法可以生成这种垫片。这里展示的方法是其中一种比较令人惊讶的方法。 程序从三个点开始&#xff08;图中圆圈所示&#xff09;。“当前位置”从其中一个点开始。为了生成后续点&…...

java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter

今天在朋友机子上运行代码&#xff0c;在生成token的时候&#xff0c;遇到了这样一个问题&#xff1a; Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter at io.jsonwebtoken.impl.Base64Codec.decode(Base64Codec.java:26) ~[jjwt-0.9.1.jar:0.…...

双因素身份验证技术在NPI区域邮件安全管控上的解决思路

在制造业中&#xff0c;NPI&#xff08;New Product Introduction&#xff0c;新产品导入&#xff09;区域是指专门负责新产品从概念到市场推出全过程的部门或团队。NPI 的目标是确保新产品能够高效、高质量地投入生产&#xff0c;并顺利满足市场需求。在支撑企业持续创新和竞争…...

java后端对接飞书登陆

java后端对接飞书登陆 项目要求对接第三方登陆&#xff0c;飞书登陆&#xff0c;次笔记仅针对java后端&#xff0c;在看本笔记前&#xff0c;默认已在飞书开发方已建立了应用&#xff0c;并获取到了appid和appsecret。后端要做的其实很简单&#xff0c;基本都是前端做的&…...

记录一次Android Studio的下载、安装、配置

目录 一、下载和安装 Android Studio 1、搜索下载Android studio ​2、下载成功后点击安装包进行安装&#xff1a; 3、这里不用打勾&#xff0c;直接点击安装 &#xff1a; 4、完成安装&#xff1a; 5、这里点击Cancel就可以了 6、接下来 7、点击自定义安装&#xff1a…...

直流无刷电机控制(FOC):电流模式

目录 概述 1 系统框架结构 1.1 硬件模块介绍 1.2 硬件实物图 1.3 引脚接口定义 2 代码实现 2.1 软件架构 2.2 电流检测函数 3 电流环功能实现 3.1 代码实现 3.2 测试代码实现 4 测试 概述 本文主要介绍基于DengFOC的库函数&#xff0c;实现直流无刷电机控制&#x…...

73.矩阵置零 python

矩阵置零 题目题目描述示例 1&#xff1a;示例 2&#xff1a;提示&#xff1a; 题解思路分析Python 实现代码代码解释提交结果 题目 题目描述 给定一个 m x n 的矩阵&#xff0c;如果一个元素为 0 &#xff0c;则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 示例…...

垃圾收集算法

分代收集理论 分代收集理论&#xff0c;建立在两个分代假说之上。 弱分代假说&#xff1a;绝大多数对象都是朝圣夕灭的。 强分代假说&#xff1a;熬过越多次垃圾收集的过程的对象就越难以消亡。 这两个分代假说奠定了垃圾收集器的一致设计原则&#xff1a;收集器应该将Java…...

SQL-leetcode-262. 行程和用户

262. 行程和用户 表&#xff1a;Trips --------------------- | Column Name | Type | --------------------- | id | int | | client_id | int | | driver_id | int | | city_id | int | | status | enum | | request_at | varchar | --------------------- id 是这张表的主键…...

太原理工大学软件设计与体系结构 --javaEE

这个是简答题的内容 选择题的一些老师会给你们题库&#xff0c;一些注意的点我会做出文档在这个网址 项目目录预览 - TYUT复习资料:复习资料 - GitCode 希望大家可以给我一些打赏 什么是Spring的IOC和DI IOC 是一种设计思想&#xff0c;它将对象的创建和对象之间的依赖关系…...

Leetcode 139. 单词拆分 动态规划

原题链接&#xff1a;Leetcode 139. 单词拆分 递归&#xff0c;超时 class Solution { public:bool isfind(string s,map<string,int>& mp){for(auto x:mp){string wordx.first;if(sword) return true;int nword.size();if(n>s.size()) continue;string s1s.subs…...

python异常机制

异常是什么&#xff1f; 软件程序在运行过程中&#xff0c;非常可能遇到刚刚提到的这些问题&#xff0c;我们称之为异常&#xff0c;英文是Exception&#xff0c;意思是例外。遇到这些例外情况&#xff0c;或者交异常&#xff0c;我们怎么让写的程序做出合理的处理&#xff0c…...

运行爬虫时可能遇到哪些常见问题?

在运行Python爬虫时&#xff0c;可能会遇到以下一些常见问题及相应的解决方法&#xff1a; 1. 请求频繁被封 IP 问题描述&#xff1a;爬虫请求频繁时&#xff0c;网站可能会识别到异常行为并封禁 IP&#xff0c;从而导致后续请求失败。解决方法&#xff1a; 使用代理&#xf…...

调用支付宝接口响应40004 SYSTEM_ERROR问题排查

在对接支付宝API的时候&#xff0c;遇到了一些问题&#xff0c;记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...

C++:std::is_convertible

C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...

Appium+python自动化(十六)- ADB命令

简介 Android 调试桥(adb)是多种用途的工具&#xff0c;该工具可以帮助你你管理设备或模拟器 的状态。 adb ( Android Debug Bridge)是一个通用命令行工具&#xff0c;其允许您与模拟器实例或连接的 Android 设备进行通信。它可为各种设备操作提供便利&#xff0c;如安装和调试…...

MFC内存泄露

1、泄露代码示例 void X::SetApplicationBtn() {CMFCRibbonApplicationButton* pBtn GetApplicationButton();// 获取 Ribbon Bar 指针// 创建自定义按钮CCustomRibbonAppButton* pCustomButton new CCustomRibbonAppButton();pCustomButton->SetImage(IDB_BITMAP_Jdp26)…...

【Go】3、Go语言进阶与依赖管理

前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课&#xff0c;做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程&#xff0c;它的核心机制是 Goroutine 协程、Channel 通道&#xff0c;并基于CSP&#xff08;Communicating Sequential Processes&#xff0…...

LLM基础1_语言模型如何处理文本

基于GitHub项目&#xff1a;https://github.com/datawhalechina/llms-from-scratch-cn 工具介绍 tiktoken&#xff1a;OpenAI开发的专业"分词器" torch&#xff1a;Facebook开发的强力计算引擎&#xff0c;相当于超级计算器 理解词嵌入&#xff1a;给词语画"…...

Caliper 配置文件解析:fisco-bcos.json

config.yaml 文件 config.yaml 是 Caliper 的主配置文件,通常包含以下内容: test:name: fisco-bcos-test # 测试名称description: Performance test of FISCO-BCOS # 测试描述workers:type: local # 工作进程类型number: 5 # 工作进程数量monitor:type: - docker- pro…...

【WebSocket】SpringBoot项目中使用WebSocket

1. 导入坐标 如果springboot父工程没有加入websocket的起步依赖&#xff0c;添加它的坐标的时候需要带上版本号。 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId> </dep…...

论文阅读:Matting by Generation

今天介绍一篇关于 matting 抠图的文章&#xff0c;抠图也算是计算机视觉里面非常经典的一个任务了。从早期的经典算法到如今的深度学习算法&#xff0c;已经有很多的工作和这个任务相关。这两年 diffusion 模型很火&#xff0c;大家又开始用 diffusion 模型做各种 CV 任务了&am…...

sshd代码修改banner

sshd服务连接之后会收到字符串&#xff1a; SSH-2.0-OpenSSH_9.5 容易被hacker识别此服务为sshd服务。 是否可以通过修改此banner达到让人无法识别此服务的目的呢&#xff1f; 不能。因为这是写的SSH的协议中的。 也就是协议规定了banner必须这么写。 SSH- 开头&#xff0c…...