skip to Main Content

I’m currently trying to make array type for my project

what I want to do is, whenever I give params to type, I want to make type base on it.

example:

 type Dimension = Number;
 type Point<Dimension, T extends Number[] = []> = Dimension extends T['length'] ? T : Point<Dimension, [...T, Number]>

 type Boundary = ??? // I wanna declare array of length 2N(double of Point<N>)


 //usage
 const x = [1,2,3] as Point<3>
 const xBoundary = [1,2,3,4,5,6] as Boundary<Point<3>>

 //usage2
 const y = [1,2,3,4] as Point<4>
 const yBoundary = [1,2,3,4,5,6,7,8] as Boundary<Point<4>>

Is this possible??

When I declare Point type, I’ve used recurisve type definition, so I’ve tried to use double recursion? and tried to spread Point type for Boundary type

e.g)

type Boundary<Point, Dimension, T extends Number[]> = Dimension extends T['length'] ? T : Point<Dimension, [...Point, ...T, Number]>;

But didn’t worked, since typescript doesn’t recognize Point as spread element and compiler accepts all Number[] types.

2

Answers


  1. Yes, you can. Here is an example.

     type Point<Length extends number, Current extends number[] = []> = Current['length'] extends Length
      ? Current
      : Point<Length, [...Current, number]>;
    
     type Boundary<T extends number[]> = [...T,...T] 
    
     //usage
     const x = [1,2,3] as Point<3>
     const xBoundary = [1,2,3,4,5,6] as Boundary<Point<3>>
    
     //usage2
     const y = [1,2,3,4] as Point<4>
     const yBoundary = [1,2,3,4,5,6,7,8] as Boundary<Point<4>>
    
    
    Login or Signup to reply.
  2. I am assuming you want to have a tuple type with twice the length, this is possible like this.

    type Tuple<
      TItem,
      TLength extends number,
      TArray extends any[] = [],
    > = TArray["length"] extends TLength
      ? TArray
      : Tuple<TItem, TLength, [...TArray, TItem]>;
    
    type DoubleLength<
      TN extends number,
      _Arr extends unknown[] = [],
    > = _Arr["length"] extends TN
      ? [..._Arr, ..._Arr]["length"]
      : DoubleLength<TN, [unknown, ..._Arr]>;
    
    type Test = Tuple<string, DoubleLength<2>>
    //   ^? [string, string, string, string]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search