TypeScript: Allow constructing float16 tensors using Float16Array
Fixes #26741
This change updates the TypeScript definitions to allow constructing float16 tensors using Float16Array in environments where it is available. Runtime behavior remains unchanged (float16 is still represented internally as Uint16Array).
- Introduces a
GlobalFloat16Arrayhelper type to safely detectFloat16Arraywithout requiring global polyfills. - Adds type-specific and inferred constructor overloads for
float16. - No changes to runtime logic or public C APIs.
This resolves compile-time errors when passing Float16Array to the Tensor constructor in the onnxruntime-web package.
Description
This PR enhances the TypeScript typings for float16 tensors within the ONNX Runtime JavaScript API:
- Adds
GlobalFloat16Array, a conditional utility type that resolves to the instance type ofFloat16Arrayonly when available. - Updates constructor definitions to accept either:
Uint16Array(existing behavior),Float16Array(new behavior, when supported by the JS environment),- or
readonly number[].
- Extends inferred-type constructors to support
new Tensor(new Float16Array(...)). - Ensures TypeScript consumers can pass
Float16Arraywithout encountering type errors.
Internally, ONNX Runtime continues to treat float16 data as Uint16Array, so runtime behavior is unchanged.
Motivation and Context
Modern JavaScript runtimes (browsers and Node versions) have begun introducing native Float16Array support. Developers using ONNX Runtime in TypeScript projects may attempt to construct float16 tensors using:
new Tensor(new Float16Array(784), [28, 28]);
@microsoft-github-policy-service agree
I think you could reuse the https://github.com/microsoft/onnxruntime/blob/790018d2fbcfcd1128352a7289c076ffa4c63120/js/common/lib/type-helper.ts#L27 helper instead of rolling custom check.
Updated to use TryGetGlobalType for Float16Array.
Let me know if you'd like any further adjustments!
Thanks for working on this! Just to be clear, I'm not a maintainer on this repo, we'll need for one of them to review too.