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

https://github.com/igorskyflyer/npm-common-types

๐Ÿ”ฆ Provides frequently used types for your TypeScript projects. ๐Ÿฆ„
https://github.com/igorskyflyer/npm-common-types

back-end common generic igorskyflyer interface javascript js node promise shared trim ts types typescript

Last synced: 5 months ago
JSON representation

๐Ÿ”ฆ Provides frequently used types for your TypeScript projects. ๐Ÿฆ„

Awesome Lists containing this project

README

          


Icon of Common Types

Common Types




๐Ÿ”ฆ Provides frequently used types for your TypeScript projects. ๐Ÿฆ„




## ๐Ÿ“ƒ Table of Contents

- [Features](#-features)
- [API](#-api)
- [KeysOf\](#keysoftype)
- [TypeOfValues\](#typeofvaluestype)
- [MethodsOf\](#methodsoftype)
- [PropertiesOf\](#propertiesoftype)
- [DeepPartial\](#deeppartialtype)
- [Promisable\](#promisabletype)
- [EnumKeys\](#enumkeystype-keytype)
- [Func](#funcargs-fnreturn)
- [Callback](#callbackargs-fnreturn)
- [TrimLeft\](#trimleftinput)
- [TrimRight\](#trimrightinput)
- [Trim\](#triminput)
- [IsGeneric\](#isgenerictype)
- [MethodSignature\](#methodsignaturetype-method)
- [Override\](#overridetype-changes)
- [HasOverlap\](#hasoverlapfirsttype-secondtype)
- [Extend\](#extendtype-changes)
- [MethodName\](#methodnametype-method)
- [Usage](#-usage)
- [API](#-api)
- [Examples](#๏ธ-examples)
- [Changelog](#-changelog)
- [Support](#-support)
- [License](#-license)
- [Related](#-related)
- [Author](#-author)




## ๐Ÿค– Features

- ๐Ÿ— Get all keys of a type with `KeysOf`
- ๐Ÿ“ฆ Extract all value types from top-level properties via `TypeOfValues`
- ๐Ÿ” Identify only method keys using `MethodsOf`
- ๐Ÿงพ Identify only property keys using `PropertiesOf`
- ๐ŸŒฟ Make every property (nested too) optional with `DeepPartial`
- โณ Accept sync or async values using `Promisable`
- ๐ŸŽฏ Find keys whose values match a specific type via `EnumKeys`
- ๐Ÿ›  Define generic function signatures with `Func` or `Callback`
- โœ‚ Remove leading/trailing whitespace in string types with `TrimLeft`, `TrimRight`, `Trim`
- โ“ Detect generic types using `IsGeneric`
- ๐Ÿ“œ Get a methodโ€™s exact signature with `MethodSignature`
- ๐Ÿ“ Override existing keys with new types via `Override`
- ๐Ÿšซ Prevent extending with overlapping keys using `Extend`
- ๐Ÿ”‘ Validate a method exists and return its name with `MethodName`




## ๐Ÿ•ต๐Ÿผ Usage

Install it by executing any of the following, depending on your preferred package manager:

```bash
pnpm add @igorskyflyer/common-types
```

```bash
yarn add @igorskyflyer/common-types
```

```bash
npm i @igorskyflyer/common-types
```




## ๐Ÿคน๐Ÿผ API

### `KeysOf`

Extracts all keys from the type `Type`.


> ๐Ÿ’ก **TIP**
>
> **CAN** be used with generics as well.
>


`example.ts`
```ts
type ArrayKeys = KeysOf> // 'at' | 'concat' | 'copyWithin', etc.
```

---

### `TypeOfValues`

Extracts all value types of the type `Type`. Works with top-level properties only.


`IPerson.ts`
```ts
interface IPerson {
firstName: string
lastName: string
zip: number
isMember: boolean
}
```


`example.ts`
```ts
type ValueTypes = TypeOfValues // string | number | boolean
```

---

### `MethodsOf`

Extracts all methods from the type `Type`.


> ๐Ÿ›‘ **CAUTION**
>
> Can **NOT** be used with generics.
>


`example.ts`
```ts
type NumberMethods = MethodsOf // 'toString' | 'toFixed' | 'toExponential' | 'toPrecision' | 'valueOf' | 'toLocaleString'
```

---

### `PropertiesOf`

Extracts all properties from the type `Type`.


> ๐Ÿ›‘ **CAUTION**
>
> Can **NOT** be used with generics.
>


`example.ts`
```ts
type StringProperties = PropertiesOf // 'length'
```

---

### `DeepPartial`

Constructs a type with all top-level and nested properties of the type `Type` set to optional.


> ๐Ÿ’ก **TIP**
>
> See also TypeScript's built-in utility type [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) ![An external link](https://raw.githubusercontent.com/igorskyflyer/igorskyflyer/main/assets/external.svg).
>


`IPerson.ts`
```ts
interface IPerson {
name: string
address: {
city: string
zip: number
}
}
```


`example.ts`
```ts
type PersonOptional = DeepPartial

/**
* PersonOptional:
* {
* name?: string
* address?: {
* city?: string
* zip?: number
* }
* }
*/
```

---

### `Promisable`

Provides a convenient way to allow flexibility in handling values that could either be immediate or asynchronously resolved.


`example.ts`
```ts
const immediateValue: number = 42
const promiseValue: Promisable = Promise.resolve(42)

async function handleValue(value: Promisable) {
const result = await processValue(value)
console.log(result) // Will log the number 42, whether value was a direct number or a Promise resolving to 42
}

handleValue(immediateValue)
handleValue(promiseValue)
```

---

### `EnumKeys`

Extracts all keys from the `Type` that are of the type `KeyType`.


`IConfig`
```ts
interface IConfig {
apiUrl: string
timeout: number
isEnabled: boolean
retryAttempts: number
}
```


`example.ts`
```ts
type ConfigNumbers = EnumKeys // 'timeout' | 'retryAttempts'
```

---

### `Func`

Constructs a generic `Function`-*like* type with the arguments of type `Args` and the return value of type `FnReturn`.


`example.ts`
```ts
function process(items: number[], callback: Func): boolean {
// shortened for brevity
// do NOT access your Array immediately :)
for (let i = 0; i < items.length; i++) {
if (callback(items[i])) {
return true
}
}

return false
}

process([1, 1, 8, 1], (item) => {
if (item % 2 === 0) {
return true
}

return false
}) // returns true
```

---

### `Callback`

Alias of [`Func`](#funcargs-fnreturn).

---

### `TrimLeft`

Recursively removes all leading whitespace from the `String` type `Input`.


`example.ts`
```ts
type Id = ' ID'
type ProperId = TrimLeft

const id: ProperId = ' ID' // ERROR: does NOT accept leading whitespace
```
---

### `TrimRight`

Recursively removes all trailing whitespace from the `String` type `Input`.


`example.ts`
```ts
type Id = 'ID '
type ProperId = TrimRight

const id: ProperId = 'ID ' // ERROR: does NOT accept leading whitespace
```
---

### `Trim`

Recursively removes all leading and trailing whitespace from the `String` type `Input`.


`example.ts`
```ts
type Id = ' ID '
type ProperId = Trim

const id: ProperId = ' ID ' // ERROR: does NOT accept leading nor trailing whitespace
```


> ๐Ÿ’ก **TIP**
>
> A very cool usage of the [`Trim`](#triminput) type is implemented in the [`magic-querySelector`](https://github.com/igorskyflyer/npm-magic-queryselector) project.
>

---

### `IsGeneric`

Returns a Boolean whether the type `Type` is a generic.


`example.ts`
```ts
type ArrayIsGeneric = IsGeneric> // true
type NumberIsGeneric = IsGeneric // false
```
---

### `MethodSignature`

Gets the method signature `Method` of the type `Type`.


`example.ts`
```ts
type NumberToFixedMethod = MethodSignature // expects (fractionDigits?: number) => string
```

---

### `Override`

Overrides the type `Type` with the new type of `Changes`.


`IPerson`
```ts
interface IPerson {
name: string
children: boolean
}
```


`example.ts`
```ts
const person: IPerson = {
name:'John Doe',
children: true
}

type NewPerson = Override //only accepts existing keys

const newPerson: NewPerson = {
name:'John Doe',
children: 2
}
```

---

### `HasOverlap`

Checks whether the types `FirstType` and `SecondType` overlap, i.e. have the same keys.


> โš ๏ธ **WARNING**
>
> It only checks the key names, **NOT** their **TYPES**!
>


`IPerson`
```ts
interface IPerson {
name: string
children: boolean
}
```


`example.ts`
```ts
type PersonOverlap = HasOverlap<
IPerson,
{
name: string
children: boolean
}
> // returns true
```
---

### `Extend`

Extends the type `Type` with the new type of `Changes` with only non-existent keys in type `Type`.


`IPerson`
```ts
interface IPerson {
name: string
children: number
}
```


`example.ts`
```ts
type NewPerson = Extend //only accepts non-existing keys
// will return `never` here
const newPerson: NewPerson = {
name: 'John Doe',
children: 2
} // will error

type NewestPerson = Extend //only accepts non-existing keys
const newestPerson: NewestPerson = {
name: 'John Doe',
children: 2,
profession: 'Developer'
} // will NOT error
```

---

### `MethodName`

Checks for the existence of the method `Method` in the type of `Type` and returns it if found.


`example.ts`
```ts
type NumberToFixedMethod = MethodName // toFixed
```

---

## ๐Ÿ—’๏ธ Examples

`utils.ts`
```ts
import type { Callback } from '@igorskyflyer/common-types'

function process(
items: number[],
callback: Callback
): boolean {
// shortened for brevity
// do NOT access your Array immediately :)
for (let i = 0; i < items.length; i++) {
if (callback(items[i])) {
return true
}
}

return false
}

const result = process([1, 1, 8, 1], (item) => {
if (item % 2 === 0) {
return true
}

return false
}) // returns true

console.log(result)

```




## ๐Ÿ“ Changelog

๐Ÿ“‘ The changelog is available here, [CHANGELOG.md](https://github.com/igorskyflyer/npm-common-types/blob/main/CHANGELOG.md).




## ๐Ÿชช License

Licensed under the MIT license which is available here, [MIT license](https://github.com/igorskyflyer/npm-common-types/blob/main/LICENSE).




## ๐Ÿ’– Support


I work hard for every project, including this one and your support means a lot to me!


Consider buying me a coffee. โ˜•




Donate to igorskyflyer




Thank you for supporting my efforts! ๐Ÿ™๐Ÿ˜Š




## ๐Ÿงฌ Related

[@igorskyflyer/windev](https://www.npmjs.com/package/@igorskyflyer/windev)

> _๐Ÿƒ Provides ways of checking whether a path is a legacy Windows device. ๐Ÿ’พ_


[@igorskyflyer/magic-queryselector](https://www.npmjs.com/package/@igorskyflyer/magic-queryselector)

> _๐Ÿช„ A TypeScript-types patch for querySelector/querySelectorAll, make them return types you expect them to! ๐Ÿ”ฎ_


[@igorskyflyer/jmap](https://www.npmjs.com/package/@igorskyflyer/jmap)

> _๐Ÿ•ถ๏ธ Reads a JSON file into a Map. ๐ŸŒป_


[@igorskyflyer/clone](https://www.npmjs.com/package/@igorskyflyer/clone)

> _๐Ÿงฌ A lightweight JavaScript utility allowing deep copy-by-value of nested objects, arrays and arrays of objects. ๐Ÿช_


[@igorskyflyer/extendable-string](https://www.npmjs.com/package/@igorskyflyer/extendable-string)

> _๐Ÿฆ€ ExtendableString allows you to create strings on steroids that have custom transformations applied to them, unlike common, plain strings.. ๐Ÿช€_






## ๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป Author
Created by **Igor Dimitrijeviฤ‡** ([*@igorskyflyer*](https://github.com/igorskyflyer/)).