Index types of object's property which is array #793
-
I have a type like: const t1 = Object({
f: Array(Object({
id: Integer()
}))
}) I wish to add another type that has a type of singular item of that array, so something like: const t2 = Object({
p: Index(t1, ['f']['number'])
}) But it does not working as it gives me an error:
I have multiple ways to solve it like declaring a separate const and using that in both types or declaring t2 first and then using that as the array item in t1. But I'm simply curious if it's possible to solve this issue in my current setup. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@hrishikesh-k Hi, You can implement this type in the following way import { Type, Static } from '@sinclair/typebox'
// type T = {
// f: ({ id: number })[]
// }
const T = Type.Object({
f: Type.Array(Type.Object({
id: Type.Integer()
}))
})
// type X = {
// p: T['f'][number]
// }
const X = Type.Object({
p: Type.Index(Type.Index(T, Type.Literal('f')), Type.Number())
}) Unfortunately, TypeBox can't support the Hope this helps! |
Beta Was this translation helpful? Give feedback.
@hrishikesh-k Hi,
You can implement this type in the following way
TypeScript Link Here
Unfortunately, TypeBox can't support the
['f'][number]
syntax, so to access deeper nested properties, you will need to use Index multiple times. Also note, for Arrays, you can passType.Number()
to access the element type.Hope this helps!
S