当前位置: 首页 > 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…...

无需联网!LongCat动物百变秀本地部署指南,动物图片编辑随心所欲

无需联网&#xff01;LongCat动物百变秀本地部署指南&#xff0c;动物图片编辑随心所欲 1. 为什么选择本地部署的动物图片编辑器&#xff1f; 在数字内容创作领域&#xff0c;动物图片编辑一直是个特殊需求。无论是宠物博主需要制作创意内容&#xff0c;还是动物保护组织要制…...

YOLOv13开箱体验:无需配置,直接运行,效果惊艳的目标检测

YOLOv13开箱体验&#xff1a;无需配置&#xff0c;直接运行&#xff0c;效果惊艳的目标检测 1. 从零开始的极速体验 作为一名长期奋战在目标检测一线的开发者&#xff0c;当我第一次接触YOLOv13官版镜像时&#xff0c;最直观的感受就是"快"。这种快不仅体现在模型推…...

Mujoco 进阶指南:程序化模型编辑与动态场景构建实战

1. 为什么需要程序化模型编辑 当你第一次接触Mujoco时&#xff0c;可能和我一样都是从XML文件开始学习的。XML确实直观易懂&#xff0c;适合初学者快速上手。但当你需要构建复杂的动态场景时&#xff0c;手动编辑XML文件就会变得异常繁琐。比如要创建一个受风力影响的树林场景&…...

实战应用全流程:基于快马平台从零到一构建并部署龙虾openclaw官网

实战应用全流程&#xff1a;基于快马平台从零到一构建并部署龙虾openclaw官网 最近在做一个AI工具库的开源项目&#xff0c;需要搭建一个展示官网。作为独立开发者&#xff0c;从零开始构建一个完整的官网涉及很多环节&#xff0c;幸好发现了InsCode(快马)平台&#xff0c;帮我…...

如何用Pulover‘s Macro Creator实现电脑自动化?免费脚本录制工具完全指南

如何用Pulovers Macro Creator实现电脑自动化&#xff1f;免费脚本录制工具完全指南 【免费下载链接】PuloversMacroCreator Automation Utility - Recorder & Script Generator 项目地址: https://gitcode.com/gh_mirrors/pu/PuloversMacroCreator 厌倦了每天重复的…...

无需电脑也能装IPA?揭秘iOS应用部署新方案

无需电脑也能装IPA&#xff1f;揭秘iOS应用部署新方案 【免费下载链接】App-Installer On-device IPA installer 项目地址: https://gitcode.com/gh_mirrors/ap/App-Installer 你是否遇到过这样的尴尬&#xff1a;出差在外想安装一个重要的IPA文件&#xff0c;却发现身边…...

嵌入式开发知识管理:基于BERT文本分割的STM32项目文档整理

嵌入式开发知识管理&#xff1a;基于BERT文本分割的STM32项目文档整理 每次接手一个老旧的STM32项目&#xff0c;你是不是也感到头疼&#xff1f;打开工程文件夹&#xff0c;里面混杂着各种版本的代码、零散的调试日志、不同工程师留下的注释&#xff0c;还有一堆硬件连接说明…...

OpenClaw自动化测试:用Phi-3-mini-128k-instruct实现CI/CD流程增强

OpenClaw自动化测试&#xff1a;用Phi-3-mini-128k-instruct实现CI/CD流程增强 1. 为什么选择OpenClawPhi-3做测试增强&#xff1f; 去年参与一个开源项目时&#xff0c;我经历了测试环节的典型困境&#xff1a;每次PR提交后&#xff0c;需要手动检查数百行日志&#xff0c;用…...

文档自由获取:kill-doc开源工具的技术解构与场景落地指南

文档自由获取&#xff1a;kill-doc开源工具的技术解构与场景落地指南 【免费下载链接】kill-doc 看到经常有小伙伴们需要下载一些免费文档&#xff0c;但是相关网站浏览体验不好各种广告&#xff0c;各种登录验证&#xff0c;需要很多步骤才能下载文档&#xff0c;该脚本就是为…...

League Akari:英雄联盟玩家的终极自动化助手与智能游戏管家

League Akari&#xff1a;英雄联盟玩家的终极自动化助手与智能游戏管家 【免费下载链接】League-Toolkit An all-in-one toolkit for LeagueClient. Gathering power &#x1f680;. 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 你是否厌倦了在英雄联盟…...