Skip to main content
numpy-ts is written in TypeScript and exports types for arrays, dtypes, and all function signatures. This guide covers patterns for writing type-safe numerical code.

Importing types

Use import type for type-only imports to ensure they are erased at compile time:
Or from the core entry point:

The DType type

DType is a string union representing all supported data types:
Use it to type dtype parameters in your functions:

NDArray vs NDArrayCore

The two array types correspond to the two main entry points: NDArray extends NDArrayCore, so every NDArray satisfies the NDArrayCore type. Both types expose the same properties: shape, ndim, size, dtype, data, strides, flags, base, itemsize, nbytes.

Writing generic functions

Accept NDArrayCore for maximum compatibility

If your function only uses standalone functions (not method chaining), accept NDArrayCore. This lets callers pass either type:

Accept NDArray when you need methods

If your function uses method chaining, require NDArray:

Pattern for library authors

If you are publishing a library that depends on numpy-ts, accept NDArrayCore in your public API and return NDArrayCore. This gives your users the choice of which entry point to use.
By depending on numpy-ts/core, your library only pulls in the functions it uses. If a consumer imports your library alongside numpy-ts, there is no duplication — the same underlying computation code is shared.

Type narrowing with dtype

The dtype property is typed as string on the array class. When you need to branch on dtype, narrow it to DType:
You can also use the utility functions isIntegerDType, isFloatDType, and isComplexDType:

Shape inference

Array shapes are exposed as readonly number[]. You can use this to write shape-aware utilities:

Combining with generics

For functions that work with multiple array types, use TypeScript generics:
Since NDArray extends NDArrayCore, a generic bounded by NDArrayCore accepts both types. The return type preserves the caller’s type through the generic parameter.

Type-safe creation functions

All creation functions accept a dtype option:
When creating arrays from data, the dtype is inferred from the values or can be explicitly set: