是否可以使用泛型创建动态数组类型?

问题描述 投票:0回答:1

我目前正在尝试为我的项目制作数组类型

我想做的是,每当我给类型提供参数时,我都想基于它来创建类型。

示例:

 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>>

这可能吗?

当我声明Point类型时,我使用了递归类型定义,所以我尝试使用双重递归?并尝试将点类型扩展到边界类型

例如)

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

但是没有用,因为打字稿无法将 Point 识别为扩展元素,并且编译器接受所有 Number[] 类型。

javascript typescript
1个回答
0
投票

是的,可以。这是一个例子。

 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>>

© www.soinside.com 2019 - 2024. All rights reserved.