3.0.3 • Published 6 months ago

@frankhoodbs/cast-prop-to-type v3.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
6 months ago

Cast Prop to Type

This utility provides a straightforward mechanism to cast various types of JavaScript properties to desired data types, such as number, array, boolean, and object. In the event of a casting error or invalid input, a custom ValidationError is thrown to provide a meaningful error message.

Version License

Usage

import { castPropToType } from "@frankhoodbs/cast-prop-to-type";

const numValue = castPropToType("42", "number");  // Returns 42 as a number

API

castPropToType(value, type)

Cast the given value to the specified type.

Parameters:

  • value (any): The value to be casted.
  • type ("number" | "array" | "boolean" | "object"): The type to which the value should be casted.

Returns:

The casted value. Throws ValidationError if casting is not possible.

ValidationError

Custom error that is thrown when there's a validation error during the casting process. It extends the native JavaScript Error class.

Examples

// Casting a string to a number
const num = castPropToType("42", "number"); // 42

// Casting a string to an array
const arr = castPropToType('["a", "b", "c"]', "array"); // ["a", "b", "c"]

// Casting a string to a boolean
const boolTrue = castPropToType("true", "boolean");  // true

// Casting a string to an object
const obj = castPropToType('{"key": "value"}', "object");  // { key: "value" }

Error Handling

If the utility encounters an invalid value for the desired casting type or if the type itself is invalid, a ValidationError will be thrown:

try {
  const num = castPropToType("foo", "number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(error.message);
  }
}
2.0.3

1 year ago

3.0.3

6 months ago

3.0.2

6 months ago

3.0.1

7 months ago

3.0.0

7 months ago

2.0.2

1 year ago

1.3.12

1 year ago

2.0.1

1 year ago

1.3.11

1 year ago

1.3.10

1 year ago

1.3.9

1 year ago

1.3.7

2 years ago

1.3.4

2 years ago

1.3.8

2 years ago

1.3.3

2 years ago

1.3.2

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.2.17

2 years ago

1.2.16

2 years ago

1.2.14

2 years ago

1.2.15

2 years ago

1.2.13

2 years ago

1.2.12

2 years ago

1.2.11

2 years ago

1.2.10

2 years ago

1.2.9

2 years ago

1.2.8

2 years ago

1.2.7

2 years ago

1.2.6

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.1

2 years ago

1.1.9

2 years ago

1.1.8

2 years ago

1.1.12

2 years ago

1.1.11

2 years ago

1.1.10

2 years ago

1.1.20

2 years ago

1.1.16

2 years ago

1.1.15

2 years ago

1.1.14

2 years ago

1.1.13

2 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.1.1

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago