打字稿在编译时减去两个数字

Typescript subtract two numbers at compile time

原问题

我需要一个实用程序类型 Subtract<A, B>,其中 AB 是数字。例如:

type Subtract<A extends number, B extends number> = /* implementation */ 
const one: Subtract<2, 1> = 1
const two: Subtract<4, 2> = 2
const error: Subtract<2, 1> = 123 // Error here: 123 is not assignable to type '1'.

Subtract<A, B> 的参数始终是数字文字或编译时常量。我不需要

let foo: Subtract<number, number> // 'foo' may have 'number' type.

已编辑问题

好的,我认为上面的文字可能是XY问题,所以我想解释一下为什么需要做减法。我有一个多维数组,它有 Dims 个维度。当调用 slice 方法时,它的维度会减少。

interface Tensor<Dimns extends number> {
    // Here `I` type is a type of indeces 
    // and its 'length' is how many dimensions 
    // are subtracted from source array.
    slice<I extends Array<[number, number]>>(...indeces: I): Tensor<Dimns - I['length']>
                                               // here I need to subtract ^ 
}

示例:

declare const arr: Tensor<4, number>
arr.slice([0, 1])               // has to be 3d array
arr.slice([0, 1], [0, 2])       // has to be 2d array
arr.slice([0, 1]).slice([0, 2]) // has to be 2d array

您可以看到 Dims 泛型如何取决于传递给 slice() 的参数数量。

如果Subtract<A, B>类型很难,是否可以递减类型?因此,我可以执行以下操作:

interface Tensor<Dimns extends number> {
    // Here `Decrement<A>` reduces the number of dimensions by 1.
    slice(start: number, end: number): Tensor<Decrement<Dimns>>
}

TypeScript 不支持编译时算法。然而,它可以被强制使用数组做一些类似的事情,但是你必须定义你自己的方法算术。我会预先警告你这绝对是可怕的。

从为数组操作定义一些基本类型开始:

type Tail<T> = T extends Array<any> ? ((...x: T) => void) extends ((h: any, ...t: infer I) => void) ? I : [] : unknown;
type Cons<A, T> = T extends Array<any> ? ((a: A, ...t: T) => void) extends ((...i: infer I) => void) ? I : unknown : never;

这些给你一些数组类型的力量,例如 Tail<['foo', 'bar']> 给你 ['bar']Cons<'foo', ['bar']> 给你 ['foo', 'bar'].

现在您可以使用基于数组的数字(不是 number)定义一些算术概念:

type Zero = [];
type Inc<T> = Cons<void, T>;
type Dec<T> = Tail<T>;

因此数字 1 在该系统中将表示为 [void],2 表示为 [void, void],依此类推。我们可以定义加减法为:

type Add<A, B> = { 0: A, 1: Add<Inc<A>, Dec<B>> }[Zero extends B ? 0 : 1];
type Sub<A, B> = { 0: A, 1: Sub<Dec<A>, Dec<B>> }[Zero extends B ? 0 : 1];

如果你有心,也可以用类似的方式定义乘除运算符。但就目前而言,这足以用作基本的算术系统。例如:

type One = Inc<Zero>;                    // [void]
type Two = Inc<One>;                     // [void, void]
type Three = Add<One, Two>;              // [void, void, void]
type Four = Sub<Add<Three, Three>, Two>; // [void, void, void, void]

定义一些其他实用方法来从 number 常量来回转换。

type N<A extends number, T = Zero> = { 0: T, 1: N<A, Inc<T>> }[V<T> extends A ? 0 : 1];
type V<T> = T extends { length: number } ? T['length'] : unknown;

现在您可以像这样使用它们了

const one: V<Sub<N<2>, N<1>>> = 1;
const two: V<Sub<N<4>, N<2>>> = 2;
const error: V<Sub<N<2>, N<1>>> = 123; // Type '123' is not assignable to type '1'.

所有这些都是为了展示 TypeScript 的类型系统有多么强大,以及您可以将它推到多远,以完成它并非真正设计的事情。它似乎也只能可靠地工作到 N<23> 左右(可能是由于 TypeScript 中递归类型的限制)。但是你真的应该在生产系统中这样做吗?

没有!

当然,这种类型滥用有点有趣(至少对我而言),但它 far 太复杂而且 far太容易犯简单的错误,而这些错误极难调试。我强烈建议您只对常量类型进行硬编码 (const one: 1),或者如评论所建议的那样,重新考虑您的设计。


对于更新后的问题,如果 Tensor 类型可以像上面 Tail 一样轻松地减少(考虑到它是一个接口,这是值得怀疑的),你可以做这样的事情:

type Reduced<T extends Tensor<number>> = T extends Tensor<infer N> ? /* construct Tensor<N-1> from Tensor<N> */ : Tensor<number>;

interface Tensor<Dimns extends number> {
  slice(start: number, end: number): Reduced<Tensor<Dimns>>;
}

但是,由于张量往往只有几个维度,我认为只需编写用户最可能需要担心的少数情况的代码就足够了:

type SliceIndeces<N extends number> = number[] & { length: N };
interface Tensor<Dims extends number> {
  slice(this: Tensor<5>, ...indeces: SliceIndeces<1>): Tensor<4>;
  slice(this: Tensor<5>, ...indeces: SliceIndeces<2>): Tensor<3>;
  slice(this: Tensor<5>, ...indeces: SliceIndeces<3>): Tensor<2>;
  slice(this: Tensor<5>, ...indeces: SliceIndeces<2>): Tensor<1>;
  slice(this: Tensor<4>, ...indeces: SliceIndeces<1>): Tensor<3>;
  slice(this: Tensor<4>, ...indeces: SliceIndeces<2>): Tensor<2>;
  slice(this: Tensor<4>, ...indeces: SliceIndeces<3>): Tensor<1>;
  slice(this: Tensor<3>, ...indeces: SliceIndeces<1>): Tensor<2>;
  slice(this: Tensor<3>, ...indeces: SliceIndeces<2>): Tensor<1>;
  slice(this: Tensor<2>, ...indeces: SliceIndeces<1>): Tensor<1>;
  slice(...indeces:number[]): Tensor<number>;
}

const t5: Tensor<5> = ...
const t3 = t5.slice(0, 5); // inferred type is Tensor<3>

我知道这会产生一些漂亮的“WET”代码,但维护此代码的成本可能仍然低于维护自定义算术系统的成本,就像我上面描述的那样。

请注意,官方 TypeScript 声明文件经常使用类似这样的模式(参见 lib.esnext.array.d.ts)。强类型定义仅涵盖最常见的用例。对于任何其他用例,用户应在适当的地方提供类型 annotations/assertions。