Coder Social home page Coder Social logo

ksxnodemodules / typescript-tuple Goto Github PK

View Code? Open in Web Editor NEW
154.0 3.0 7.0 210 KB

Generics to work with tuples in TypeScript

Home Page: https://www.npmjs.com/package/typescript-tuple

License: MIT License

TypeScript 100.00%
typescript tuple generic

typescript-tuple's Introduction

TypeScript Tuple

Generics to work with tuples in TypeScript

Requirements

  • TypeScript โ‰ฅ 4.1.0

Usage

IsFinite

import { IsFinite } from 'typescript-tuple'

type Foo = IsFinite<[0, 1, 2]> // Expect: true
const foo: Foo = true

type Bar = IsFinite<[0, 1, 2, ...number[]]> // Expect: false
const bar: Bar = false

type Baz = IsFinite<[0, 1, 2], 'finite', 'infinite'> // Expect: 'finite'
const baz: Baz = 'finite'

First

import { First } from 'typescript-tuple'
type Foo = First<['a', 'b', 'c']> // Expect: 'a'
const foo: Foo = 'a'

Last

import { Last } from 'typescript-tuple'
type Foo = Last<['a', 'b', 'c']> // Expect: 'c'
const foo: Foo = 'c'

Tail

import { Tail } from 'typescript-tuple'
type Foo = Tail<['a', 'b', 'c']> // Expect: ['b', 'c']
const foo: Foo = ['b', 'c']

Append

import { Append } from 'typescript-tuple'
type Foo = Append<['a', 'b', 'c'], 'x'> // Expect: ['a', 'b', 'c', 'x']
const foo: Foo = ['a', 'b', 'c', 'x']

Prepend

import { Prepend } from 'typescript-tuple'
type Foo = Prepend<['a', 'b', 'c'], 'x'> // Expect: ['x', 'a', 'b', 'c']
const foo: Foo = ['x', 'a', 'b', 'c']

Reverse

import { Reverse } from 'typescript-tuple'
type Foo = Reverse<['a', 'b', 'c']> // Expect: ['c', 'b', 'a']
const foo: Foo = ['c', 'b', 'a']

Concat

import { Concat } from 'typescript-tuple'
type Foo = Concat<['a', 'b', 'c'], [0, 1, 2]> // Expect ['a', 'b', 'c', 0, 1, 2]
const foo: Foo = ['a', 'b', 'c', 0, 1, 2]

Repeat

import { Repeat } from 'typescript-tuple'

// Basic
type Foo = Repeat<'x', 5> // Expect ['x', 'x', 'x', 'x', 'x']
const foo: Foo = ['x', 'x', 'x', 'x', 'x']

// Using union
type Bar = Repeat<'x', 1 | 3 | 4> // Expect ['x'] | ['x', 'x', 'x'] | ['x', 'x', 'x', 'x']
const bar1: Bar = ['x']
const bar3: Bar = ['x', 'x', 'x']
const bar4: Bar = ['x', 'x', 'x', 'x']

// Using ambiguous 'number' type
type Baz = Repeat<'x', number> // Expect 'x'[]
const baz: Baz = Array<number>()

NOTES:

  • Due to TypeScript design limitations, using floating point numbers and negative numbers might lead to infinite loop within TSC compiler, avoid doing this.

ConcatMultiple

import { ConcatMultiple } from 'typescript-tuple'
type Foo = ConcatMultiple<[[], ['a'], ['b', 'c']]> // Expect ['a', 'b', 'c']
const foo: Foo = ['a', 'b', 'c']

Drop

import { Drop } from 'typescript-tuple'

type Foo = Drop<[0, 1, 2, 3, 4], 2> // Expect [2, 3, 4]
const foo: Foo = [2, 3, 4]

type Bar = Drop<[0, 1, 2, 3, 4, ...number[]], 2> // Expect [2, 3, 4, ...number[]]
const bar: Bar = [2, 3, 4]

type Baz = Drop<[0, 1, 2, 3, 4], 10> // Expect []
const baz: Baz = [2, 3, 4]

type Qux = Drop<[0, 1, 2, 3, 4, ...number[]], 10> // Expect number[]
const qux: Qux = [2, 3, 4]

SliceStartQuantity

import { SliceStartQuantity } from 'typescript-tuple'
type Foo = SliceStartQuantity<[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2, 4> // Expect [2, 3, 4, 5]
const foo: Foo = [2, 3, 4, 5]

FillTuple

import { FillTuple } from 'typescript-tuple'
type Foo = FillTuple<[0, 1, 2, 3], 'r'>
const foo: Foo = ['r', 'r', 'r', 'r']

CompareLength

import { CompareLength } from 'typescript-tuple'

type Foo = CompareLength<[0, 1, 2], ['a', 'b', 'c']> // Expect: 'equal'
const foo: Foo = 'equal'

type Bar = CompareLength<[0, 1], ['a', 'b', 'c', 'd']> // Expect: 'shorterLeft'
const bar: Bar = 'shorterLeft'

type Baz = CompareLength<[0, 1, 2, 3], ['a', 'b']> // Expect: 'shorterRight'
const baz: Baz = 'shorterRight'

SortTwoTuple

import { SortTwoTuple } from 'typescript-tuple'

type Foo = SortTwoTuple<[0, 1], ['a', 'b', 'c', 'd']> // Expect: [[0, 1], ['a', 'b', 'c', 'd']]
const foo: Foo = [[0, 1], ['a', 'b', 'c', 'd']]

type Bar = SortTwoTuple<[0, 1, 2, 3], ['a', 'b']> // Expect: [['a', 'b'], [0, 1, 2, 3]]
const bar: Bar = [['a', 'b'], [0, 1, 2, 3]]

type Baz = SortTwoTuple<[0, 1, 2], ['a', 'b', 'c', 'd']> // Expect: [[0, 1, 2], ['a', 'b', 'c']]
const baz: Baz = [[0, 1], 3, ['a', 'b', 'c']]

type Qux = SortTwoTuple<[0, 1, 2], ['a', 'b', 'c', 'd'], 'EQUAL'> // Expect: 'EQUAL'
const qux: Qux = 'EQUAL'

ShortestTuple

import { ShortestTuple } from 'typescript-tuple'

type Foo = ShortestTuple<[[0, 1, 2], [false, true], ['a', 'b', 'c', 'd']]> // Expect: [false, true]
const foo: Foo = [false, true]

type Bar = ShortestTuple<[[0, 1, 2], ['a', 'b', 'c'], ...[false, true][]]> // Expect: [false, true]
const bar: Bar = [false, true]

LongestTuple

import { LongestTuple } from 'typescript-tuple'

type Foo = LongestTuple<[[0, 1, 2, 3], [false, true], ['a']]> // Expect: [0, 1, 2, 3]
const foo: Foo = [0, 1, 2, 3]

type Bar = LongestTuple<[[], [false, true], ...[0, 1, 2][]]> // Expect: [0, 1, 2]
const bar: Bar = [0, 1, 2]

FilterTuple

import { FilterTuple } from 'typescript-tuple'

type Foo = FilterTuple<[1, '1'], number> // Expect: [1]
const foo: Foo = [1]

type Bar = FilterTuple<[1, '1', null, true], 1 | '1' | true> // Expect: [1, '1', true]
const bar: Bar = [1, '1', true]

License

MIT @ Hoร ng Vฤƒn Khแบฃi

typescript-tuple's People

Contributors

artalar avatar ksxgithub avatar renovate-bot avatar totalolage 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

typescript-tuple's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • typescript-compare ^0.0.2
  • typescript ~4.2.0
  • tslint ^6.1.3
  • tslint-config-standard ^9.0.0
  • static-type-assert ^4.0.1
  • toolcheck ^0.1.4
  • clean-typescript-build ^0.1.5
travis
.travis.yml
  • node 10

  • Check this box to trigger a request for Renovate to run again on this repository

Reversing a readonly tuple

I have this tuple of functions and I am trying to reverse it.

    namespace Utils {
        export type IsFinite<Tuple extends any[], Finite, Infinite> = {
            empty: Finite
            nonEmpty: ((..._: Tuple) => any) extends ((_: infer First, ..._1: infer Rest) => any)
            ? IsFinite<Rest, Finite, Infinite>
            : never
            infinite: Infinite
        }[
            Tuple extends [] ? 'empty' :
            Tuple extends (infer Element)[] ?
            Element[] extends Tuple ?
            'infinite'
            : 'nonEmpty'
            : never
        ]

        export type Prepend<Tuple extends any[], Addend> =
            ((_: Addend, ..._1: Tuple) => any) extends ((..._: infer Result) => any) ? Result : never


        export type Reverse<Tuple extends any[], Prefix extends any[] = []> = {
            empty: Prefix,
            nonEmpty: ((..._: Tuple) => any) extends ((_: infer First, ..._1: infer Next) => any)
            ? Reverse<Next, Prepend<Prefix, First>>
            : never
            infinite: {
                ERROR: 'Cannot reverse an infinite tuple'
                CODENAME: 'InfiniteTuple'
            }
        }[
            Tuple extends [any, ...any[]]
            ? IsFinite<Tuple, 'nonEmpty', 'infinite'>
            : 'empty'
        ]
    }

    export type ReadFuncs = readonly ((x: any) => any)[]
    export type Reverse<Tuple extends ReadFuncs> = Utils.Reverse<Tuple>

Playground

Add support for readonly tuples

With TS 3.4 it became common practice to create tuples with [a, b, c] as const. This is really convenient, however the resulting tuple is readonly. It would be awesome to add support for these readonly tuples, right now I get error readonly (something) is not assignable to any[].

Implementing Reverse

I attempted implementing reverse. For some reason the types work sometimes in a straight forward manner ( see reverse1 below ) and sometimes backwards ( see reverse2 ). Is this a bug or is this how it is supposed to work?

function reverse1<A extends Array<any>>(a: A): Reverse<A> {
  return (a.reverse() as unknown) as Reverse<A>;
}

function reverse2<A extends Array<any>>(a: Reverse<A>): A {
  return (a.reverse() as unknown) as A;
}

'Type expected' error

This library was added to my project after updating another library dependency. I am using v2.2.1. I get a Type expected error from this library when building my source on the following lines:

typescript-tuple/lib/index.d.ts(19,47)
typescript-tuple/lib/index.d.ts(156,60)
typescript-tuple/lib/index.d.ts(161,59)
typescript-tuple/lib/utils.d.ts(13,87)
typescript-tuple/lib/utils.d.ts(64,23)

What causes this? Is the issue fixed in a newer release?

Append function

Can I somehow write a function "append" that takes a random tuple and appends something to it?

Example:

append([1,'2',3], true) // should be [1,'2',3,true]
append([], 1) // should be [1]

I have tried something like this:

function append<A extends any[], V>(a: A, v: V): Append<A, V>;

but I keep receiving "Infinite Tuple" Error.

I was wondering if you could help me.

Drop has infinite instantiation

The Drop type has an infinite instantiation when used in a generic

Drop<any[], number>; // This throws an "infinite instantiation" error
Drop<[], number>;    // The first parameter is specific, the second generic, this is OK
Drop<any[], 0>;      // The first parameter is generic, the second specific, this is also OK

[Feature]: Add "recursivePluck" (tuple as index type)

Feature request

Ive recently been looking for ages to find a type-save implementation of recursively plucking an object via a tuple (explaination below). As I was unable to find any solution online, I resorted to posting a stackoverflow question which was answered brilliantly by @maciejsikora very recently.

Would you be open to adopting this type here? Before diving in to the depths of the internet to find a solution for my problem, I was aware of typescript-tuple (searching typescript-tuple was actually the first thing I did when researching). Hence my request to adopt it here. I understand if you consider this off topic here, since it is not purely of tuple domain. If so, Id gald if you could point me in a direction (maybe another library) where this feature would be better suited.

type Test1 = RecursivePluck<{a: {b: {c: {e: string}}, d: string}}, ['a','d']> // typeof string
type Test2 = RecursivePluck<{a: {b: {c: string}, d: string}},['a', 'b']> // typeof {c: string}

Here the implemantation by @maciejsikora.

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.