npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@igor.dvlpr/common-types

v1.3.0

Published

🔦 Provides frequently used types for your TypeScript projects. 🦄

Downloads

1

Readme

📃 Table of contents


🕵🏼 Usage

Install it by executing:

npm i -D "@igor.dvlpr/common-types"

🤹🏼 API

KeysOf<Type>

Extracts all keys from the type Type.

[!TIP] CAN be used with generics as well.

example.ts

type ArrayKeys = KeysOf<Array<string>> // 'at' | 'concat' | 'copyWithin', etc.

TypeOfValues<Type>

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

IPerson.ts

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

example.ts

type ValueTypes = TypeOfValues<IPerson> // string | number | boolean

MethodsOf<Type>

Extracts all methods from the type Type.

[!CAUTION] Can NOT be used with generics.

example.ts

type NumberMethods = MethodsOf<Number> // 'toString' | 'toFixed' | 'toExponential' | 'toPrecision' | 'valueOf' | 'toLocaleString'

PropertiesOf<Type>

Extracts all properties from the type Type.

[!CAUTION] Can NOT be used with generics.

example.ts

type StringProperties = PropertiesOf<String> // 'length'

DeepPartial<Type>

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<Type> An external link.

IPerson.ts

interface IPerson {
  name: string
  address: {
    city: string
    zip: number
  }
}

example.ts

type PersonOptional = DeepPartial<IPerson>

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

Promisable<Type>

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

example.ts

const immediateValue: number = 42
const promiseValue: Promisable<number> = Promise.resolve(42)

async function handleValue(value: Promisable<number>) {
  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<Type, KeyType>

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

IConfig

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

example.ts

type ConfigNumbers = EnumKeys<IConfig, number> // 'timeout' | 'retryAttempts'

Func<Args, FnReturn>

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

example.ts

function process(items: number[], callback: Func<number, boolean>): 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<Args, FnReturn>

Alias of Func<Args, FnReturn>.


TrimLeft<Input>

Recursively removes all leading whitespace from the String type Input.

example.ts

type Id = '    ID'
type ProperId = TrimLeft<Id>

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

TrimRight<Input>

Recursively removes all trailing whitespace from the String type Input.

example.ts

type Id = 'ID     '
type ProperId = TrimRight<Id>

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

Trim<Input>

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

example.ts

type Id = '    ID     '
type ProperId = Trim<Id>

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

[!TIP] A very cool usage of the Trim<Input> type is implemented in the magic-querySelector project.


IsGeneric<Type>

Returns a Boolean whether the type Type is a generic.

example.ts

type ArrayIsGeneric = IsGeneric<Array<string>> // true
type NumberIsGeneric = IsGeneric<number> // false

MethodSignature<Type, Method>

Gets the method signature Method of the type Type.

example.ts

type NumberToFixedMethod = MethodSignature<Number, 'toFixed'> // expects (fractionDigits?: number) => string

Override<Type, Changes>

Overrides the type Type with the new type of Changes.

IPerson

interface IPerson {
  name: string
  children: boolean
}

example.ts

const person: IPerson = {
  name:'John Doe',
  children: true
}

type NewPerson = Override<IPerson, { children: number }> //only accepts existing keys

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

HasOverlap<FirstType, SecondType>

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

interface IPerson {
  name: string
  children: boolean
}

example.ts

type PersonOverlap = HasOverlap<
  IPerson,
  {
    name: string
    children: boolean
  }
> // returns true

Extend<Type, Changes>

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

IPerson

interface IPerson {
  name: string
  children: number
}

example.ts

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

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

MethodName<Type, Method>

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

example.ts

type NumberToFixedMethod = MethodName<Number, 'toFixed'> // toFixed

✨ Examples

utils.ts

import type { Callback } from '@igor.dvlpr/common-types'

function process(
  items: number[],
  callback: Callback<number, boolean>
): 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

📑 Changelog is available here: CHANGELOG.md.


🪪 License

Licensed under the MIT license which is available here, MIT license.


🧬 Related

@igor.dvlpr/windev

🍃 Provides ways of checking whether a path is a legacy Windows device. 💾

@igor.dvlpr/magic-queryselector

🪄 A TypeScript-types patch for querySelector/querySelectorAll, make them return types you expect them to! 🔮

@igor.dvlpr/jmap

🕶️ Reads a JSON file into a Map. 🌻

@igor.dvlpr/node-clone-js

🧬 A lightweight JavaScript utility allowing deep copy-by-value of nested objects, arrays and arrays of objects. 🪁

@igor.dvlpr/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).