Home > Back-end >  type/interface = object or array of object
type/interface = object or array of object

Time:11-09

I need a type/interface to define a property that can be object or an array. The problem with typescript | operator is that if I use it I will have to explicitly check each time if the variable is array or not but I always know if its an object or an array. So instead I ended up using as SomeType or as SomeType[]. What I want is to not have to do it.

So current idea is to create a mixture of object and array, so that instead of array checks or "as" assertions I will have to add ?. everywhere.

My current solution is

interface _Array<T> extends Array<T | undefined> {}
type ArrayORObject<T> = Partial<T> & Partial<_Array<T>>;

Which almost works but the only issue is that now I'm getting "Index signature for type 'number' is missing in type SomeObject", seems that it requires objects to have Array index signature ([index: number]), but I can't figure out if its possible to have optional index signature.

Edit: Thanks for suggesting "satisfies" but bumping TS to beta version not really an option rn. adding call to makeOrder() isn't much better then creating some function that will check if array.

Better example enter image description here

b) use the value inside if where you check its type enter image description here

code

  • Related