#Typing known array of objects

16 messages · Page 1 of 1 (latest)

fickle citrus
#

I have this array. With the current type definition, I still get a type error when trying to use either key (e.g. Type 'Vector3 | Euler' is not assignable to type 'Vector3 | undefined'.

How would I best type this?

const data: Array<Record<string, Vector3 | Euler>> = [
  {
    position: [0, 0, -20],
    rotation: [0, 0, 0],
  },
  {
    position: [0, 0, 20],
    rotation: [0, 0, 0],
  },
  {
    position: [25, 0, 0],
    rotation: [0, angleToRadians(90), 0],
  },
  {
    position: [-25, 0, 0],
    rotation: [0, angleToRadians(-90), 0],
  },
];```
prime zephyr
#

Not exactly sure what you are asking for because a lot of the information is missing, but seems like you want to use satisfies instead:

const data = [
    // ...
] satisfies Array<Record<string, Vector3 | Euler>>
fickle citrus
#

I'm definitely not trying to use satisfies

prime zephyr
#

Have you tried it? It sounds like it would solve your problem.

fickle citrus
#

The error I get above is when I try to do, for example, data[0].position

prime zephyr
#

If it doesn't, then you need to provide more information, there isn't types for Vector3, Euler, or what's causing the error when you try to use data[0].position. Make a TS reproduction would be good.

royal fjord
#

you say that data contains objects that might be Vector3 or Euler, but you're trying to assign to something that wants a Vector3

royal fjord
#

but we don't

prime zephyr
#

We don't know what they are.

royal fjord
#

also we don't know the context

#

a description on what you're trying to achieve with data would be nice

fickle citrus
#

Okay sorry for the confusion. Let me try to explain differently. so I'm getting this error when using, for example data[0].position Type 'Vector3 | Euler' is not assignable to type 'Vector3 | undefined'. Type 'Euler' is not assignable to type 'Vector3 | undefined'. and when using data[0].rotation I'm getting this error Type 'Vector3 | Euler' is not assignable to type 'Euler | undefined'. Type 'number' is not assignable to type 'Euler | undefined'.

I'm trying to figure out, how can I write the type definition for data such that TS knows data[0].position is of type Vector3 and data[0].rotation is of type Euler

royal fjord
#

just to clarify; we understand your error; we don't understand why you wrote the code that caused it. just that last line is what we need

#

your Record<string, Vector3 | Euler> says that you have objects where any string keys might have a Vector3 or a Euler value, but that's not what you want
you wanted this:

data[0].position is of type Vector3 and data[0].rotation is of type Euler
so write that. Array<{ position: Vector3; rotation: Euler }>