如何创建灵活函数检查数组元素类型与指定类型数组匹配?
Got it, let's break down how to build this flexible type-checking function without hardcoding anything. The goal is to validate that each element in your arguments array matches the corresponding type constructor in your syntax array, ignoring any extra arguments beyond the length of syntax.
Native JavaScript Solution
First, we need a helper function to handle the type check correctly—since primitive values (like 23 or 'hello') don't pass the instanceof check for their wrapper constructors (e.g., 23 instanceof Number returns false), we need to account for both primitives and their object counterparts.
Step 1: Helper Function for Type Matching
function isTypeMatch(value, expectedType) { // Handle null/undefined explicitly if needed if (value === null) return expectedType === null; if (value === undefined) return expectedType === undefined; // Check for primitive number/string/boolean (both literal and wrapper object) switch (expectedType) { case Number: return typeof value === 'number' || value instanceof Number; case String: return typeof value === 'string' || value instanceof String; case Boolean: return typeof value === 'boolean' || value instanceof Boolean; // For reference types (Object, Array, custom classes), use instanceof default: return value instanceof expectedType; } }
Step 2: Main Validation Function
This function loops through each type in your syntax array, checks the corresponding argument, and ignores any extra arguments:
function validateArgs(syntax, args) { // Iterate over each required type in the syntax array for (let i = 0; i < syntax.length; i++) { const arg = args[i]; // If the argument is missing (fewer args than syntax), return false if (arg === undefined) return false; // Check if the argument matches the expected type if (!isTypeMatch(arg, syntax[i])) return false; } // All required arguments match; extra args are ignored return true; }
Testing with Your Example
const syntax = [Number, String]; const arguments = [23, 'some string', { some: 'ignored argument' }]; console.log(validateArgs(syntax, arguments)); // Output: true
This works for custom classes too! For example:
class User {} const userSyntax = [User, String]; const userArgs = [new User(), 'admin']; console.log(validateArgs(userSyntax, userArgs)); // Output: true
Using an NPM Module (If You Need More Power)
If you want to handle more complex type scenarios (like optional arguments, arrays of specific types, or union types), the type-check module is a great choice.
Install the Module
npm install type-check
Example Usage
const { typeCheck } = require('type-check'); function validateArgsWithModule(syntax, args) { // Convert the syntax array to a type string (e.g., "[Number, String]") const typeString = `[${syntax.map(type => type.name).join(', ')}]`; // Only check the first N arguments (matching syntax length) const relevantArgs = args.slice(0, syntax.length); return typeCheck(typeString, relevantArgs); } // Test it console.log(validateArgsWithModule(syntax, arguments)); // Output: true
This module supports more advanced type definitions, like [Number, Maybe String] for optional arguments or [Array Number] for arrays of numbers—super handy for complex validation needs.
Edge Cases to Consider
- Missing Arguments: If your
argumentsarray is shorter thansyntax, the function returnsfalse(you can adjust this to allow optional types by modifying the helper function). - Null/Undefined: The helper function explicitly checks for these if you need to validate against them (e.g.,
syntax = [null, undefined]). - Primitive vs Wrapper Objects: Both
23andnew Number(23)will match theNumbertype.
内容的提问来源于stack exchange,提问作者Rek

