Open
Description
Feature Request: Strong compile-time typing for Tensor shape in TypeScript
System information
- TensorFlow.js version (you are using): latest (
@tensorflow/tfjs-node
) - Are you willing to contribute it: Yes
🔧 Describe the feature and the current behavior/state
TensorFlow.js has great support for JavaScript and TypeScript, but its type system does not currently enforce shape correctness or tensor operations at compile-time.
This proposal is for a type-level system for tensors, allowing shape, dtype, and operation safety to be validated by the TypeScript compiler — inspired by projects like torch.typing
and the Type Challenges.
The proposed types would allow constructs like the following:
const tensor1 = new Tensor([1, 2, 3] as const);
// Tensor<[3], "float32">
const tensor2 = new Tensor([
[1, 2, 3],
[4, 5, 6]
] as const);
// Tensor<[2, 3], "float32">
const tensor3 = new Tensor([[1, 2], [3, 4, 5], 6] as const);
// TFJSTypeError<"The array's dimensions are not consistent">
const tensor4 = new Tensor(someData, [3, 3] as const);
// Ensures shape compatibility at runtime
Operations would preserve or manipulate type-level shape:
const summed = tensor2.sum(); // Tensor<[], "float32">
const alongDim = tensor2.sum(1); // Tensor<[2], "float32">
const invalid = tensor2.sum(2); // TFJSTypeError<"Given 'dim' 2 is out of bounds">
Shape transformations:
const reshaped = tensor4.reshape([9, 1] as const);
// Tensor<[9, 1], "float32">
const invalidReshape = tensor4.reshape([4, 3] as const);
// TFJSTypeError<"Cannot reshape tensor of size 9 (shape [3, 3]) into shape [4, 3] (size 12)">
Dtype change:
const tensorBool = tensor4.asType('bool')
// Tensor<[3, 3], "bool">
Will this change the current API? How?
No. The implementation can be done in a non-invasive way by adding an advanced type layer on top of the current tensor system.
- It would be purely additive: a
TypedTensor
orStaticTensor
can wrap existing tensors. - A possible separate namespace or type overloads may be used.
Who will benefit with this feature?
- TypeScript users who want compile-time safety for tensor shape and dtype.
- Developers building scientific, ML, or mathematical tools on top of TensorFlow.js.
- Educators and learners who want better feedback from the compiler when doing tensor manipulation.