torch.IsAtLeast1D
export type IsAtLeast1D<S extends Shape> = S['length'] extends 0
? false
: number extends S['length']
? true
: true;Sextends ShapeType guard to check if a shape is at least 1-dimensional (not a scalar).
Returns true if the shape has at least one dimension, false for scalars (rank 0).
Useful for constraining functions to operate on non-scalar tensors only.
Shape Constraint:
- Scalars have shape
[](empty tuple) with rank 0 → returnsfalse - Vectors, matrices, and higher-rank tensors → return
true - Dynamic shapes (rank unknown) → return
true(optimistic)
Use Cases:
- Constraining generic functions to reject scalar inputs
- Type-safe error messages when scalar operations fail
- Guarding operations that require at least one dimension
Examples
// Scalar shape: rank 0
type scalarShape = readonly [];
type check1 = IsAtLeast1D<scalarShape>; // false
// Vector shape: rank 1
type vectorShape = readonly [5];
type check2 = IsAtLeast1D<vectorShape>; // true
// Matrix shape: rank 2
type matrixShape = readonly [3, 4];
type check3 = IsAtLeast1D<matrixShape>; // true
// Dynamic shape (unknown rank)
type dynamicShape = readonly number[];
type check4 = IsAtLeast1D<dynamicShape>; // true (optimistic)
// Use in function constraints
function flattenFirst<S extends Shape>(
tensor: Tensor<S>,
// Only accept if S is at least 1D
...args: IsAtLeast1D<S> extends true ? [options?: Options] : never
): Tensor {
// Implementation
}