Code Monkey home page Code Monkey logo

utility-types's Introduction

utility-types

Collection of utility types, complementing TypeScript built-in mapped types and aliases (think "lodash" for static types).

Latest Stable Version NPM Downloads NPM Downloads Bundlephobia Size

CI Check License Join the community on Spectrum

Found it useful? Want more updates?

Show your support by giving a ⭐

Buy Me a Coffee Become a Patron



What's new?

🎉 Added new utilities 🎉



Features

Goals

  • Quality - thoroughly tested for type correctness with type-testing library dts-jest
  • Secure and minimal - no third-party dependencies
  • No runtime cost - it's type-level only

Installation

# NPM
npm install utility-types

# YARN
yarn add utility-types

Compatibility Notes

TypeScript support

  • v3.x.x - TypeScript v3.1+
  • v2.x.x - TypeScript v2.8.1+
  • v1.x.x - TypeScript v2.7.2+

Funding Issues

Utility-Types is an open-source project created by people investing their time for the benefit of our community.

Issues like bug fixes or feature requests can be very quickly resolved when funded through the IssueHunt platform.

I highly recommend adding a bounty to the issue that you're waiting for to attract some contributors willing to work on it.

Let's fund issues in this repository

Contributing

We are open for contributions. If you're planning to contribute please make sure to read the contributing guide as it can save you from wasting your time: CONTRIBUTING.md


  • (built-in) - types built-in TypeScript, no need to import

Table of Contents

Aliases & Type Guards

Union operators

Object operators

Special operators

Flow's Utility Types

Deprecated API (use at own risk)

  • getReturnOfExpression() - from TS v2.0 it's better to use type-level ReturnType instead

Primitive

Type representing primitive types in JavaScript, and thus TypeScript: string | number | bigint | boolean | symbol | null | undefined

You can test for singular of these types with typeof

isPrimitive

This is a TypeScript Typeguard for the Primitive type.

This can be useful to control the type of a parameter as the program flows. Example:

const consumer = (param: Primitive[] | Primitive): string => {
    if (isPrimitive(param)) {
        // typeof param === Primitive
        return String(param) + ' was Primitive';
    }
    // typeof param === Primitive[]
    const resultArray = param
        .map(consumer)
        .map(rootString => '\n\t' + rootString);
    return resultArray.reduce((comm, newV) => comm + newV, 'this was nested:');
};

⇧ back to top

Falsy

Type representing falsy values in TypeScript: false | "" | 0 | null | undefined

Except NaN which cannot be represented as a type literal

isFalsy

const consumer = (param: Falsy | string): string => {
    if (isFalsy(param)) {
        // typeof param === Falsy
        return String(param) + ' was Falsy';
    }
    // typeof param === string
    return param.toString();
};

⇧ back to top

Nullish

Type representing nullish values in TypeScript: null | undefined

⇧ back to top

isNullish

const consumer = (param: Nullish | string): string => {
    if (isNullish(param)) {
        // typeof param === Nullish
        return String(param) + ' was Nullish';
    }
    // typeof param === string
    return param.toString();
};

⇧ back to top

SetIntersection<A, B> (same as Extract)

Set intersection of given union types A and B

Usage:

import { SetIntersection } from 'utility-types';

// Expect: "2" | "3"
type ResultSet = SetIntersection<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: () => void
type ResultSetMixed = SetIntersection<string | number | (() => void), Function>;

⇧ back to top

SetDifference<A, B> (same as Exclude)

Set difference of given union types A and B

Usage:

import { SetDifference } from 'utility-types';

// Expect: "1"
type ResultSet = SetDifference<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: string | number
type ResultSetMixed = SetDifference<string | number | (() => void), Function>;

⇧ back to top

SetComplement<A, A1>

Set complement of given union types A and (it's subset) A1

Usage:

import { SetComplement } from 'utility-types';

// Expect: "1"
type ResultSet = SetComplement<'1' | '2' | '3', '2' | '3'>;

⇧ back to top

SymmetricDifference<A, B>

Set difference of union and intersection of given union types A and B

Usage:

import { SymmetricDifference } from 'utility-types';

// Expect: "1" | "4"
type ResultSet = SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>;

⇧ back to top

NonNullable<A>

Exclude null and undefined from set A

⇧ back to top

NonUndefined<A>

Exclude undefined from set A

⇧ back to top

Exclude<A, B>

Exclude subset B from set A

⇧ back to top

Extract<A, B>

Extract subset B from set A

⇧ back to top

Operations on objects

FunctionKeys<T>

Get union type of keys that are functions in object type T

Usage:

import { FunctionKeys } from 'utility-types';

type MixedProps = { name: string; setName: (name: string) => void };

// Expect: "setName"
type Keys = FunctionKeys<MixedProps>;

⇧ back to top

NonFunctionKeys<T>

Get union type of keys that are non-functions in object type T

Usage:

import { NonFunctionKeys } from 'utility-types';

type MixedProps = { name: string; setName: (name: string) => void };

// Expect: "name"
type Keys = NonFunctionKeys<MixedProps>;

⇧ back to top

MutableKeys<T>

Get union type of keys that are mutable (not readonly) in object type T

Alias: WritableKeys<T>

Usage:

import { MutableKeys } from 'utility-types';

type Props = { readonly foo: string; bar: number };

// Expect: "bar"
type Keys = MutableKeys<Props>;

⇧ back to top

ReadonlyKeys<T>

Get union type of keys that are readonly in object type T

Usage:

import { ReadonlyKeys } from 'utility-types';

type Props = { readonly foo: string; bar: number };

// Expect: "foo"
type Keys = ReadonlyKeys<Props>;

⇧ back to top

RequiredKeys<T>

Get union type of keys that are required in object type T

Usage:

import { RequiredKeys } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };

// Expect: "req" | "reqUndef"
type Keys = RequiredKeys<Props>;

⇧ back to top

OptionalKeys<T>

Get union type of keys that are optional in object type T

Usage:

import { OptionalKeys } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };

// Expect: "opt" | "optUndef"
type Keys = OptionalKeys<Props>;

⇧ back to top

UnionKeys<U>

Get keys of all objects in the union type U

Usage:

import { UnionKeys } from 'utility-types';

type Props = { name: string } | { age: number } | { visible: boolean };

// Expect: "name" | "age" | "visible"
type Keys = UnionKeys<Props>;

⇧ back to top

Optional<T, K>

From T make a set of properties by key K become optional

Usage:

import { Optional } from 'utility-types';

type Props = { name: string; age: number; visible: boolean; };

// Expect: { name?: string; age?: number; visible?: boolean; }
type Props = Optional<Props>
// Expect: { name: string; age?: number; visible?: boolean; }
type Props = Optional<Props, 'age' | 'visible'>;

⇧ back to top

Pick<T, K> (built-in)

From T pick a set of properties by key K

Usage:

type Props = { name: string; age: number; visible: boolean };

// Expect: { age: number; }
type Props = Pick<Props, 'age'>;

⇧ back to top

PickByValue<T, ValueType>

From T pick a set of properties by value matching ValueType. (Credit: Piotr Lewandowski)

Usage:

import { PickByValue } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; };

// Expect: { req: number }
type Props = PickByValue<Props, number>;
// Expect: { req: number; reqUndef: number | undefined; }
type Props = PickByValue<Props, number | undefined>;

⇧ back to top

PickByValueExact<T, ValueType>

From T pick a set of properties by value matching exact ValueType.

Usage:

import { PickByValueExact } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; };

// Expect: { req: number }
type Props = PickByValueExact<Props, number>;
// Expect: { reqUndef: number | undefined; }
type Props = PickByValueExact<Props, number | undefined>;

⇧ back to top

Omit<T, K>

From T remove a set of properties by key K

Usage:

import { Omit } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };

// Expect: { name: string; visible: boolean; }
type Props = Omit<Props, 'age'>;

⇧ back to top

OmitByValue<T, ValueType>

From T remove a set of properties by value matching ValueType. (Credit: Piotr Lewandowski)

Usage:

import { OmitByValue } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; };

// Expect: { reqUndef: number | undefined; opt?: string; }
type Props = OmitByValue<Props, number>;
// Expect: { opt?: string; }
type Props = OmitByValue<Props, number | undefined>;

⇧ back to top

OmitByValueExact<T, ValueType>

From T remove a set of properties by value matching exact ValueType.

Usage:

import { OmitByValueExact } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; };

// Expect: { reqUndef: number | undefined; opt?: string; }
type Props = OmitByValueExact<Props, number>;
// Expect: { req: number; opt?: string }
type Props = OmitByValueExact<Props, number | undefined>;

⇧ back to top

Intersection<T, U>

From T pick properties that exist in U

Usage:

import { Intersection } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };

// Expect: { age: number; }
type DuplicatedProps = Intersection<Props, DefaultProps>;

⇧ back to top

Diff<T, U>

From T remove properties that exist in U

Usage:

import { Diff } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };

// Expect: { name: string; visible: boolean; }
type RequiredProps = Diff<Props, DefaultProps>;

⇧ back to top

Subtract<T, T1>

From T remove properties that exist in T1 (T1 has a subset of the properties of T)

Usage:

import { Subtract } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };

// Expect: { name: string; visible: boolean; }
type RequiredProps = Subtract<Props, DefaultProps>;

⇧ back to top

Overwrite<T, U>

From U overwrite properties to T

Usage:

import { Overwrite } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
type NewProps = { age: string; other: string };

// Expect: { name: string; age: string; visible: boolean; }
type ReplacedProps = Overwrite<Props, NewProps>;

⇧ back to top

Assign<T, U>

From U assign properties to T (just like object assign)

Usage:

import { Assign } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
type NewProps = { age: string; other: string };

// Expect: { name: string; age: string; visible: boolean; other: string; }
type ExtendedProps = Assign<Props, NewProps>;

⇧ back to top

ValuesType<T>

Get the union type of all the values in an object, tuple, array or array-like type T.

Usage:

import { ValuesType } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
// Expect: string | number | boolean
type PropsValues = ValuesType<Props>;

type NumberArray = number[];
// Expect: number
type NumberItems = ValuesType<NumberArray>;

type ReadonlyNumberTuple = readonly [1, 2];
// Expect: 1 | 2
type AnotherNumberUnion = ValuesType<NumberTuple>;

type BinaryArray = Uint8Array;
// Expect: number
type BinaryItems = ValuesType<BinaryArray>;

⇧ back to top

Partial<T>

Make all properties of object type optional

⇧ back to top

Required<T, K>

From T make a set of properties by key K become required

Usage:

import { Required } from 'utility-types';

type Props = { name?: string; age?: number; visible?: boolean; };

// Expect: { name: string; age: number; visible: boolean; }
type Props = Required<Props>
// Expect: { name?: string; age: number; visible: boolean; }
type Props = Required<Props, 'age' | 'visible'>;

⇧ back to top

Readonly<T>

Make all properties of object type readonly

⇧ back to top

Mutable<T>

From T make all properties become mutable

Alias: Writable<T>

import { Mutable } from 'utility-types';

type Props = {
  readonly name: string;
  readonly age: number;
  readonly visible: boolean;
};

// Expect: { name: string; age: number; visible: boolean; }
Mutable<Props>;

⇧ back to top

ReturnType<T>

Obtain the return type of a function

⇧ back to top

InstanceType<T>

Obtain the instance type of a class

⇧ back to top

Unionize<T>

Disjoin object to form union of objects, each with single property

Usage:

import { Unionize } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };

// Expect: { name: string; } | { age: number; } | { visible: boolean; }
type UnionizedType = Unionize<Props>;

⇧ back to top

PromiseType<T>

Obtain Promise resolve type

Usage:

import { PromiseType } from 'utility-types';

// Expect: string
type Response = PromiseType<Promise<string>>;

⇧ back to top

DeepReadonly<T>

Readonly that works for deeply nested structures

Usage:

import { DeepReadonly } from 'utility-types';

type NestedProps = {
  first: {
    second: {
      name: string;
    };
  };
};

// Expect: {
//   readonly first: {
//     readonly second: {
//       readonly name: string;
//     };
//   };
// }
type ReadonlyNestedProps = DeepReadonly<NestedProps>;

⇧ back to top

DeepRequired<T>

Required that works for deeply nested structures

Usage:

import { DeepRequired } from 'utility-types';

type NestedProps = {
  first?: {
    second?: {
      name?: string;
    };
  };
};

// Expect: {
//   first: {
//     second: {
//       name: string;
//     };
//   };
// }
type RequiredNestedProps = DeepRequired<NestedProps>;

⇧ back to top

DeepNonNullable<T>

NonNullable that works for deeply nested structure

Usage:

import { DeepNonNullable } from 'utility-types';

type NestedProps = {
  first?: null | {
    second?: null | {
      name?: string | null | undefined;
    };
  };
};

// Expect: {
//   first: {
//     second: {
//       name: string;
//     };
//   };
// }
type RequiredNestedProps = DeepNonNullable<NestedProps>;

⇧ back to top

DeepPartial<T>

Partial that works for deeply nested structures

Usage:

import { DeepPartial } from 'utility-types';

type NestedProps = {
  first: {
    second: {
      name: string;
    };
  };
};

// Expect: {
//   first?: {
//     second?: {
//       name?: string;
//     };
//   };
// }
type PartialNestedProps = DeepPartial<NestedProps>;

⇧ back to top

Brand<T, U>

Define nominal type of U based on type of T. Similar to Opaque types in Flow.

Usage:

import { Brand } from 'utility-types';

type USD = Brand<number, "USD">
type EUR = Brand<number, "EUR">

const tax = 5 as USD;
const usd = 10 as USD;
const eur = 10 as EUR;

function gross(net: USD): USD {
  return (net + tax) as USD;
}

gross(usd); // ok
gross(eur); // Type '"EUR"' is not assignable to type '"USD"'.

⇧ back to top

UnionToIntersection<U>

Get intersection type given union type U

Usage:

import { UnionToIntersection } from 'utility-types';

// Expect: { name: string } & { age: number } & { visible: boolean }
UnionToIntersection<{ name: string } | { age: number } | { visible: boolean }>

⇧ back to top


Flow's Utility Types

$Keys<T>

get the union type of all the keys in an object type T
https://flow.org/en/docs/types/utilities/#toc-keys

Usage:

import { $Keys } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };

// Expect: "name" | "age" | "visible"
type PropsKeys = $Keys<Props>;

⇧ back to top

$Values<T>

get the union type of all the values in an object type T
https://flow.org/en/docs/types/utilities/#toc-values

Usage:

import { $Values } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };

// Expect: string | number | boolean
type PropsValues = $Values<Props>;

⇧ back to top

$ReadOnly<T>

get the read-only version of a given object type T
https://flow.org/en/docs/types/utilities/#toc-readonly

Usage:

import { $ReadOnly } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };

// Expect: Readonly<{ name: string; age: number; visible: boolean; }>
type ReadOnlyProps = $ReadOnly<Props>;

⇧ back to top

$Diff<T, U>

get the set difference of a given object types T and U (T \ U)
https://flow.org/en/docs/types/utilities/#toc-diff

Usage:

import { $Diff } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };

// Expect: { name: string; visible: boolean; }
type RequiredProps = $Diff<Props, DefaultProps>;

⇧ back to top

$PropertyType<T, K>

get the type of property of an object at a given key K
https://flow.org/en/docs/types/utilities/#toc-propertytype

Usage:

import { $PropertyType } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
// Expect: string
type NameType = $PropertyType<Props, 'name'>;

type Tuple = [boolean, number];
// Expect: boolean
type A = $PropertyType<Tuple, '0'>;
// Expect: number
type B = $PropertyType<Tuple, '1'>;

⇧ back to top

$ElementType<T, K>

get the type of elements inside of array, tuple or object of type T, that matches the given index type K
https://flow.org/en/docs/types/utilities/#toc-elementtype

Usage:

import { $ElementType } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };
// Expect: string
type NameType = $ElementType<Props, 'name'>;

type Tuple = [boolean, number];
// Expect: boolean
type A = $ElementType<Tuple, 0>;
// Expect: number
type B = $ElementType<Tuple, 1>;

type Arr = boolean[];
// Expect: boolean
type ItemsType = $ElementType<Arr, number>;

type Obj = { [key: string]: number };
// Expect: number
type ValuesType = $ElementType<Obj, string>;

⇧ back to top

$Call<T>

get the return type of a given expression type
https://flow.org/en/docs/types/utilities/#toc-call

The built-in ReturnType can be used to accomplish the same goal, although it may have some subtle differences.

Usage:

import { $Call } from 'utility-types';

// Common use-case
const add = (amount: number) => ({ type: 'ADD' as 'ADD', payload: amount });
type AddAction = $Call<typeof add>; // { type: 'ADD'; payload: number }

// Examples migrated from Flow docs
type ExtractPropType<T extends { prop: any }> = (arg: T) => T['prop'];
type Obj = { prop: number };
type PropType = $Call<ExtractPropType<Obj>>; // number
// type Nope = $Call<ExtractPropType<{ nope: number }>>; // Error: argument doesn't match `Obj`.

type ExtractReturnType<T extends () => any> = (arg: T) => ReturnType<T>;
type Fn = () => number;
type FnReturnType = $Call<ExtractReturnType<Fn>>; // number

⇧ back to top

$Shape<T>

Copies the shape of the type supplied, but marks every field optional.
https://flow.org/en/docs/types/utilities/#toc-shape

Usage:

import { $Shape } from 'utility-types';

type Props = { name: string; age: number; visible: boolean };

// Expect: Partial<Props>
type PartialProps = $Shape<Props>;

⇧ back to top

$NonMaybeType<T>

Converts a type T to a non-maybe type. In other words, the values of $NonMaybeType<T> are the values of T except for null and undefined.
https://flow.org/en/docs/types/utilities/#toc-nonmaybe

Usage:

import { $NonMaybeType } from 'utility-types';

type MaybeName = string | null;

// Expect: string
type Name = $NonMaybeType<MaybeName>;

⇧ back to top

Class<T>

Given a type T representing instances of a class C, the type Class is the type of the class C
https://flow.org/en/docs/types/utilities/#toc-class * Differs from original Flow's util - implements only constructor part and won't include any static members. Additionally classes in Typescript are not treated as nominal

Usage:

import { Class } from 'utility-types';


function makeStore(storeClass: Class<Store>): Store {
  return new storeClass();
}

⇧ back to top

mixed

An arbitrary type that could be anything (same as unknown)
https://flow.org/en/docs/types/mixed

⇧ back to top


Related Projects

  • ts-toolbelt - Higher type safety for TypeScript
  • $mol_type - Collection of TypeScript meta types for complex logic

License

MIT License

Copyright (c) 2016 Piotr Witek mailto:[email protected] (http://piotrwitek.github.io)

utility-types's People

Contributors

9smtm6 avatar aaronjensen avatar airtoxin avatar axure avatar bboydflo avatar cyli2014 avatar dimitropoulos avatar dosentmatter avatar ersimont avatar filipomar avatar gamtiq avatar goodmind avatar kumar303 avatar levenleven avatar malash avatar mcampagonzalez avatar mpiniarski avatar nin-jin avatar ozum avatar piotrwitek avatar promer94 avatar rahgurung avatar shanamaid avatar spencersutton avatar thejohnfreeman avatar vatosarmat avatar wongwill86 avatar yuddomack avatar zhirzh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

utility-types's Issues

Update internal type correctness unit-test framework to dts-jest

Historically typesafe-actions was created well before there was any solutions in the wild that would allow to unit-test correctness of resulting type annotations.
So I had to improvise and cook my own solution to do that, unfortunately this increased a cost of maintenance and adding new features slowing down development and increasing effort.

UPDATE: After that I spend some time investigating options it turned out npm-ramda project uses another library dts-jest which is exactly what I was looking for.

This task is updated to use dts-jest for type testing.

This will allow to add new features with less effort and also increase the type correctness unit-test coverage.

Planned work:

  • remove internal types testing framework
  • refactor all existing tests to use dtslint

React utility types ( eg React.ElementProps )

So since conditional types have been introduced, i found out how to do this.
Been wanting this for ages.

Flow (i think its right)...you get the point

const TestComponent = ({one}: {one: number}) => <div>{one}</div>

type TestProps = React.ElementProps<typeof TestComponent>
// TestProps = {one: number}

Typescript:

type ElementProps<T> = T extends React.ComponentType<infer Props>
  ? Props extends object ? Props : never
  : never;

const TestComponent = ({one}: {one: number}) => <div>{one}</div>;

type TestProps = ElementProps<typeof TestComponent>;
// TestProps = {one: number}

ElementProps is really just TypeOfFirstArg but using react's component types

So maybe also worth adding:

type FirstArg<T extends Function> = T extends (arg: infer A) => any ? A : never;

Not sure if thats the best way and if iv used the best types in react. Maybe best to not add react stuff to this library?

Rename UnboxPromise to PromiseType

Renaming UnboxPromise to PromiseType because it's name sound too much like a function call and also to follow the spirit of similar API in standard lib, for instance:

  • in TS: ReturnType, InstanceType
  • in Flow: $PropertyType, $ElementType

Don't panic because UnboxPromise will stay for a while being marked as deprecated, to give users time to refactor.

3.6.0 bug

I just updated and my code is broken. I extracted the problematic part.

interface NextLinkProps2 {
  prefetch?: boolean;
  shallow?: boolean;
  scroll?: boolean;
  replace?: boolean;
  onError?(error: any): void;
  href?: string;
  as?: string;
  passHref?: boolean;
  children: React.ReactElement;
}

type AppHref = {
    pathname: "/";
}

export type LinkProps = Assign<
  Overwrite<
    Omit<NextLinkProps2, 'passHref'>,
    {
      // Allow string etc.
      children: ReactNode;
      // Make href required and typed.
      href: AppHref;
    }
  >,
  {
    accessible?: boolean;
    download?: string;
    // style?: StyleProp<TextStyle>;
    // activeStyle?: StyleProp<TextStyle>;
    // We use it for manual focus.
    nativeID?: string;
  }
>;

const foo: LinkProps = { prefetch: true, href: { pathname: '/' } };
Type '{ prefetch: true; href: { pathname: "/"; }; }' is missing the following properties from type 'Pick<Pick<Pick<Pick<Omit<NextLinkProps2, "passHref">, "prefetch" | "shallow" | "scroll" | "replace" | "onError" | "as"> & Pick<{ children: ReactNode; href: { pathname: "/"; } | { pathname: "/me"; } | { ...; } | { ...; } | ({ ...; } & { ...; }); }, "href" | "children">, "prefetch" |

Add new alias: mixed

Issuehunt badges

Should this also include

declare type mixed = unknown

?

Also it would be more useful if all Flow types would be globals


IssueHunt Summary

goodmind goodmind has been rewarded.

Backers (Total: $20.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

2.2.0 published in NPM does not contain class ActionCreator

2.2.0's tagged code and documentation references the new "ActionCreator" class.
Unfortunately the version published on NPM does not contain this class despite being tagged as 2.2.0 too.

Maybe you accidentally published an older version with the new tag.

Brand is not exported

import { Brand } from "utility-types" throws an error "Module ... has no exported member 'Brand'"

v3.4.1

returntypeof should return undefined

better to return undefined than empty object to introduce explicit error rather than fail silently in cases when you mistakenly use it as a mapper function in redux connect helper

PickType and OmitType

Hi,

Could you please add PickType and OmitType types similar to Pick and Omit. It would be helpful. They pick and omit properties based on types of values instead of key names:

I changed names to make it more compatible with utility-types. You can change if you have a more appropriate name in your mind.

Types

// From `Base` pick a set of properties with types of `Condition`
type PickType<Base, Condition> = Pick<Base, { [Key in keyof Base]: Base[Key] extends Condition ? Key : never }[keyof Base]>;

// From `Base` remove a set of properties with types of `Condition`
type OmitType<Base, Condition> = Pick<Base, { [Key in keyof Base]: Base[Key] extends Condition ? never : Key }[keyof Base]>;

Usage

type Props = { name: string; age: number; visible: boolean };

type SomeProps = PickType<Props, string | number>;
// Expect: { name: string; age: number }

type OtherProps = OmitType<Props, string | number>;
// Expect: { visible: boolean }

Types are not developed by me. I saw them on a blog post by Piotr Lewandowski and used in several projects.
Credits: https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c

Thanks,

Add new type: UnionToIntersection

Issuehunt badges

type UnionToIntersection<U extends object> = (U extends any ? (k: U) => void : never) extends ((
  k: infer I,
) => void)
  ? I
  : never;

A use case:

function mergeObjects<T extends object>(args: Array<T>): UnionToIntersection<T> {
  return args.reduce((prev, curr) => ({ ...prev, ...curr }), {} as UnionToIntersection<T>);
}

const a = { a: 1 };
const b = { b: true };
const c = { c: 'hi' };
const merged = mergeObjects([a, b, c]);
// merged is { a: number } & { b: boolean } & { c: string }

Ref: https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type


IssueHunt Summary

dosentmatter dosentmatter has been rewarded.

Backers (Total: $20.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

DeepRequired Type

The TypeScript standard library includes a Required type, but this only operates on the top-most level of fields in a type. A DeepRequired type, perhaps something like this, would be useful.

interface Example {
  foo?: { bar?: number }
}

// Required<Example>
{
  foo: { bar?: number }
}

// DeepRequired<Example>
{
  foo: { bar: number }
}

$ObjMap support

I'm not sure if it's possible (either way might be good to document).

Improve organization and add missing examples in API documentation

Table of contents needs improvements in organization for better user experience, also we are missing some built-in examples.
Here is a rough plan of needed improvements:

  • Improve api list organization and grouping (operations on object keys)
  • Add missing built-in types (Record, Parameters, ConstructorParameters)
  • Add missing use-case examples to standard-lib API
  • Add Optional type alias for Partial

Support for typescript 2.7.1 ?

Recently updated to typescript 2.7.1 and faced an issue with at-loader. No big issue I'll downgrade to typescript 2.6, just to let you know.

 ERROR in [at-loader] ./node_modules/utility-types/es5-commonjs/mapped-types.d.ts:13:93 
[0]     TS2344: Type '({ [P in keyof T]: P; } & {} & { [k: string]: never; })[keyof T]' does not satisfy the constraint 'keyof (Pick<T, ({ [P in keyof T]: P; } & { [P in keyof U]: never; } & { [k: string]: never; })[ke...'.
[0]   Type '({ [P in keyof T]: P; } & {})[keyof T]' is not assignable to type 'keyof (Pick<T, ({ [P in keyof T]: P; } & { [P in keyof U]: never; } & { [k: string]: never; })[ke...'.
[0]     Type '{ [P in keyof T]: P; }[keyof T]' is not assignable to type 'keyof (Pick<T, ({ [P in keyof T]: P; } & { [P in keyof U]: never; } & { [k: string]: never; })[ke...'.
[0]       Type 'keyof T' is not assignable to type 'keyof (Pick<T, ({ [P in keyof T]: P; } & { [P in keyof U]: never; } & { [k: string]: never; })[ke...'.
[0]         Type 'keyof T' is not assignable to type 'never'.
[0]           Type '{ [P in keyof T]: P; }[keyof T]' is not assignable to type 'never'.
[0]             Type '({ [P in keyof T]: P; } & {})[keyof T]' is not assignable to type 'never'.
[0]               Type '({ [P in keyof T]: P; } & {} & { [k: string]: never; })[keyof T]' is not assignable to type 'never'.
[0]                 Type '({ [P in keyof T]: P; } & {})[keyof T]' is not assignable to type 'never'.
[0]                   Type '{ [P in keyof T]: P; }[keyof T]' is not assignable to type 'never'.
[0]                     Type 'keyof T' is not assignable to type 'never'.

Proposal Brand type

branded type is known as nominal type in other language.

Demo

type Brand<K, T> = K & { __brand: T }

type USD = Brand<number, "USD">
type EUR = Brand<number, "EUR">

const usd = 10 as USD;
const eur = 10 as EUR;

function gross(net: USD, tax: USD): USD {
  return (net + tax) as USD;
}

gross(usd, usd); // ok
gross(eur, usd); // Type '"EUR"' is not assignable to type '"USD"'.

Reference: https://michalzalecki.com/nominal-typing-in-typescript/

Naming of _brand property and Brand type is convention in typescript team.
https://github.com/Microsoft/TypeScript/search?utf8=%E2%9C%93&q=brand&type=

Missing Types

I just pulled the latest with npm but I noticed there are missing types. (e.g. Unionize). I took a look at the node_modules folder and I noticed that the build files are not matching the src files.

Version: 2.0.0

_DeepReadonlyArray does not count as array

For the following code:

import { DeepReadonly } from 'utility-types';

type Thing = { prop: string };
type Arr = DeepReadonly<Thing[]>;

function first<T>(arr: T[]) {
  return arr[0];
}

const arr: Arr = [{ prop: 'foo' }];
const initial = first(arr);

I get:

Argument of type '_DeepReadonlyArray<Thing>' is not assignable to parameter of type '_DeepReadonlyObject<Thing>[]'.
  Type '_DeepReadonlyArray<Thing>' is missing the following properties from type '_DeepReadonlyObject<Thing>[]': pop, push, reverse, shift, and 3 more.ts(2345)

Proposal ParameterType

example:

export type Parameter1Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: infer Parameter1, ...parameters: any[]) => any ? Parameter1 : never;
export type Parameter2Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: infer Parameter2, ...parameters: any[]) => any ? Parameter2 : never;
export type Parameter3Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: any, parameter3: infer Parameter3, ...parameters: any[]) => any ? Parameter3 : never;
export type Parameter4Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: any, parameter3: any, parameter4: infer Parameter4, ...parameters: any[]) => any ? Parameter4 : never;
export type Parameter5Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: any, parameter3: any, parameter4: any, parameter5: infer Parameter5, ...parameters: any[]) => any ? Parameter5 : never;
export type Parameter6Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: any, parameter3: any, parameter4: any, parameter5: any, parameter6: infer Parameter6, ...parameters: any[]) => any ? Parameter6 : never;
export type Parameter7Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: any, parameter3: any, parameter4: any, parameter5: any, parameter6: any, parameter7: infer Parameter7, ...parameters: any[]) => any ? Parameter7 : never;
export type Parameter8Type<Fun extends (...parameters: any[]) => any> = Fun extends (parameter1: any, parameter2: any, parameter3: any, parameter4: any, parameter5: any, parameter6: any, parameter7: any, parameter8: infer Parameter8, ...parameters: any[]) => any ? Parameter8 : never;

function generateParameterOverloads(n: number) {
    const params = Array.from(range(1, n));
    return params.map(typeTemplate).join(";\n");
    function typeTemplate(i: number) {
        return `export type Parameter${i}Type<Fun extends (...parameters: any[]) => any> = Fun extends ${inferClause(
            i
        )} ? Parameter${i} : never`;
    }
    function inferClause(i: number) {
        return `(${params
            .slice(0, i - 1)
            .map(anyParamter)
            .concat([
                `parameter${i}: infer Parameter${i}`,
                `...parameters: any[]`
            ])
            .join(", ")}) => any`;
    }
    function anyParamter(k: number) {
        return `parameter${k}: any`;
    }
}

function* range(start: number, end: number): IterableIterator<number> {
    for (let i = start; i <= end; i++) {
        yield i;
    }
}

Add a web page with API documentation that will be automatically generated from the recent source code changes

I would be nice to have a nice API Documentation webpage with search functionality similar to Ramda: https://ramdajs.com/docs/

API documentation requirements:

A recommended solution is to parse source files (which now contains usage examples in JSDoc comments) to generate a markdown based static documentation website.

One way is to use a full documentation generator to generate a website from source files (I'm open to suggestions if you can find something but I guess TypeScript support will be required, maybe this: https://dotnet.github.io/docfx/).

Another way would be to use a JSDoc => Markdown transformer (like jsdoc2md) and then add some custom scripts to do the rest and use it as a page in a markdown docs generator like Docsaurus or Docz.

Additional alternatives to investigate:

Add new type: Mutable

Issuehunt badges

I think that there are not a type for mutable object

export type Mutable<T> = {
    -readonly [P in keyof T]: T[P];
};

IssueHunt Summary

dosentmatter dosentmatter has been rewarded.

Backers (Total: $20.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

New API Proposal for extending Pick/Omit and Object-Keys Helpers

I agree we could greatly benefit from both general helpers and shortcuts.

New API Proposal for extending Pick/Omit and Object-Keys Helpers

General:

we need to have consistent convention between Keys and Pick helpers and have variations for matching by assignability and exact type

  • PickByValue<TObj, TValue>

  • PickByExactValue<TObj, TValue>

  • OmitByValue<TObj, TValue>

  • OmitByExactValue<TObj, TValue>

  • KeysByValue<TObj, TValue> === keyof PickByValue<TObj, TValue> - no need to implement

  • KeysByExactValue<TObj, TValue> === keyof PickByExactValue<TObj, TValue> - no need to implement

Shortcuts:

Existing:

  • FunctionKeys
  • NonFunctionKeys
  • ReadonlyKeys
  • WritableKeys

New:

  • RequiredKeys #53
  • OptionalKeys #53

Open for feedback/improvements!

Flow's Class<T>

Class<T>

Given a type T representing instances of a class C, the type Class is the type of the class C

Similar can be achieved in Typescript by typeof Foo but requires Foo to be a value, not a type. So can't be used with generics

Constructor part can be easily described by: type Constructor<T> = new (...args) => T;. This of course won't include any static members and won't verify inheritance (classes in Typescript not treated as nominal)

Maybe it is good enough to include only "constructor part"?

ActionCreator without payload

ActionCreator without payload - require payload anyway

ActionCreators.testAction.create => ...testAction(null)

One change:

export declare class ActionCreator<T, P> {
    readonly type: T;
    readonly payload: P;
    constructor(type: T);
    create: (payload: P) => { // payload => payload?
        type: T;
        payload: P;
    };
}

Add new type: ValuesType

Issuehunt badges

Proposal to add ValuesType, looking for feedback:

export type ValuesType<T extends ArrayLike[] | Record<string, any>> = T extends ArrayLike[]
  ? T[number]
  : T extends object
  ? T[keyof T]
  : never;

const arr = [1, 2];
const obj = { key: 'value' };

type t1 = typeof arr[number];
type t2 = typeof obj[keyof typeof obj]; // this is really mouthful and I was annoyed by this many times

// consistent and simple
type t3 = ValuesType<typeof arr>; // number
type t4 = ValuesType<typeof obj>; // string

IssueHunt Summary

axure axure has been rewarded.

Backers (Total: $25.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

What is meant by "Provides multiple output formats"?

I want to start using this library, but was surprised to read that it "Provides multiple output formats (es5-commonjs, es5-module, jsnext)". Isn't this library simply Typescript? I'd like to leave the compilation to Typescript and/or Babel.

Omit type doesn't work for deconstructor with rest

Please see the minimal reproducible example below and questions inline.

type TGeneric<T extends string = string> = Extract<
    | {pet: 'dog', age: number}
    | {pet: 'cat', age: number}
,
    {pet: T, age: number}
>

const someScope = <T extends 'dog' | 'cat' = 'dog'>(arg1: TGeneric<T>) => {
    const {age, ...rest} = arg1

    let A: Omit<TGeneric<T>, 'age'> = rest
    //  ^ I expect this to work, but it complains, why?

    let B: Pick<TGeneric<T>, SetDifference<keyof TGeneric<T>, 'age'>> = rest
    //  ^ From Error message above I figured out a type that doesn't complain. 
    //    What's the difference? Is this expected behavior?
}

New Suggestions

I don't know how or if you'd like suggestions like this, but I just found this library, I'd like to use it, and it would be cool to get some more of the utility types I use from here. Happy to move any of these that sound interesting to a separate issue, or to just close this if none of them do.

export interface ClassFor<T> {
  new (...args: unknown[]): T;
}

export interface ObjectWith<T> {
  [key: string]: T;
}

/** @hidden */
export interface NumberKeyedObject<T = unknown> {
  [key: number]: T;
}

export type Primitive = number | boolean | string;
export type Existant = Primitive | object;
export type Nil = null | undefined;
export type Falsey = Nil | false | 0 | ""; // | NaN

export type Function0<R> = () => R;
export type Function1<T1, R> = (t1: T1) => R;
export type Function2<T1, T2, R> = (t1: T1, t2: T2) => R;
export type Function3<T1, T2, T3, R> = (t1: T1, t2: T2, t3: T3) => R;
export type Function4<T1, T2, T3, T4, R> = (
  t1: T1,
  t2: T2,
  t3: T3,
  t4: T4,
) => R;

export type Transformer<T> = (input: T) => T;

warnings from build process using react-redux-typescript returntypeof()

I am finding returntypeof very useful, I am getting some warnings from my build process.

using node 6.11.0
using npm 3.10.10
using [email protected]
using [email protected]
using [email protected]

I have tried the following import methods.

import { returntypeof } from 'react-redux-typescript';
import { returntypeof } from 'react-redux-typescript/module';
import { returntypeof } from 'react-redux-typescript/esnext';
import { returntypeof } from 'react-redux-typescript/es5';

On windows 10.

I am getting the following warnings, things do seem to be working otherwise.

WARNING in ./~/react-redux-typescript/module/index.js
(Emitted value instead of an instance of Error) Cannot find source file '../src/index.ts': Error: Can't resolve '../src/index.ts' in 'C:\dev\qk-enhanced\Enhanced.Eylm.MyFamilyLounge\node_modules\react-redux-typescript\module'
 @ ./src/containers/appRoot.tsx 7:31-64
 @ ./src/containers/app.tsx
 @ ./src/main.tsx

WARNING in ./~/react-redux-typescript/module/helpers.js
(Emitted value instead of an instance of Error) Cannot find source file '../src/helpers.ts': Error: Can't resolve '../src/helpers.ts' in 'C:\dev\qk-enhanced\Enhanced.Eylm.MyFamilyLounge\node_modules\react-redux-typescript\module'
 @ ./~/react-redux-typescript/module/index.js 6:0-26
 @ ./src/containers/appRoot.tsx
 @ ./src/containers/app.tsx
 @ ./src/main.tsx

WARNING in ./~/react-redux-typescript/module/returntypeof.js
(Emitted value instead of an instance of Error) Cannot find source file '../src/returntypeof.ts': Error: Can't resolve '../src/returntypeof.ts' in 'C:\dev\qk-enhanced\Enhanced.Eylm.MyFamilyLounge\node_modules\react-redux-typescript\module'
 @ ./~/react-redux-typescript/module/index.js 8:0-31
 @ ./src/containers/appRoot.tsx
 @ ./src/containers/app.tsx
 @ ./src/main.tsx

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.