Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/natescarlet/cast-unknown

Cast unknown value to desired type with typescript support.
https://github.com/natescarlet/cast-unknown

cast typescript

Last synced: 2 months ago
JSON representation

Cast unknown value to desired type with typescript support.

Awesome Lists containing this project

README

        

# Cast Unknown

[![build status](https://github.com/NateScarlet/cast-unknown/workflows/Node%20CI/badge.svg)](https://github.com/NateScarlet/cast-unknown/actions)
[![npm package](https://img.shields.io/npm/v/cast-unknown)](https://www.npmjs.com/package/cast-unknown)

Cast unknown value to desired type with typescript support.

Throws `CastError` when value is invalid.

Current supported cast target:

- string
- number
- object
- array
- date
- promise
- iterable
- sole item (one and the only one item from given iterable, otherwise undefined)
- nonNull (not null or undefined)

```javascript
import {
castString,
castNumber,
castObject,
castArray,
castDate,
castPromise,
castIterable,
castSoleItem,
castNonNull,
CastError,
} from 'cast-unknown';

castString(1);
// '1'
castNumber('2');
// 2
castObject(3);
//
castArray(4);
// [4]
castArray([5]);
// [5]
castArray(null);
// []
castArray(undefined);
// []
castArray([null]);
// [null]
castArray([undefined]);
// [undefined]
castDate('2019-01-01 12:00');
//
castPromise(6);
// async () => 6
castPromise(() => 7);
// async () => 7
castPromise(async () => 8);
// async () => 8
castIterable(9);
// [9]
const generator = (function* () {
for (let i; i < 10; i++) {
yield i;
}
})();
castIterable(generator);
// generator
castIterable(null);
// []
castIterable(undefined);
// []
castOne(11);
// 11
castOne([12, 13]);
// undefined
castOne([14]);
// 14
castNonNull(15);
// 15
castNonNull(null);
//
castNonNull(undefined);
//
```

## related

- [cast-unknown-python](https://github.com/NateScarlet/cast-unknown-python)