#FixedUint8Array

4 messages · Page 1 of 1 (latest)

weak star
#

Is there a way to encode the length of typed arrays in the type?
My naive approach of extending Uint8Array with a literal type in it's length doesn't seem to cut it. 😅

#typedarray #dependenttypes

gritty pastureBOT
#
somethingelseentire#0

Preview:```ts
interface FixedUint8Array<L extends number>
extends Uint8Array {
length: L
}

const a: FixedUint8Array<16> = new Uint8Array(16)```

vagrant orbit
#

this type does what you want:
type FixedUint8Array<L extends number> = Uint8Array & { length: L }
the issue is that you cant assign a regular Uint8Array to it since the length type returned by that is just number instead of a literal number, so youll need to cast the result instead:

gritty pastureBOT
#
littlelily#0

Preview:ts ... const a: FixedUint8Array<16> = new Uint8Array(16); // unfortunately this doesnt work ...