-1

I'm having trouble with TypeScript interface.

I've always made some easy interfaces like below.

{ a: 1 }

interface A {
    a: number 
}

but this time I am very lost.

Here is the result that my function returns and I want to make an interface for it.

  [
   [ 0 ],
   {
     acknowledged: true,
     modifiedCount: 1,
     upsertedId: null,
     upsertedCount: 0,
     matchedCount: 1
   }
 ]

It is an array which has an another array and an object inside.

I will be glad for you help.

Thank you !

Emily
  • 1
  • 2
  • What have you tried so far? Where are you having difficulties specifically? Do you need your interface to be a _view_ over existing data? Does it need to be immutable or mutable? etc – Dai Dec 23 '21 at 01:52
  • The example JSON you posted has an _outer type_ that's an Array, not an `object`. It's not usual to define an interface that describes an array (but it can be done). We can't really proceed any further until you clarify what you're doing. – Dai Dec 23 '21 at 01:53
  • Hi Dai ! I feel sorry for not clarifying clearly, I am very new in programming. I mean I want do make an folder that has all the interfaces inside and export to use. One of the functions in my code returns the result likeabove I wrote (an array and there is an array and an object inside) so I want to know how to define a type for this result. – Emily Dec 23 '21 at 02:08
  • Seen this? https://stackoverflow.com/questions/25469244/how-can-i-define-an-interface-for-an-array-of-objects – Dai Dec 23 '21 at 02:33
  • Yep I've solved it! Thanks Dai – Emily Dec 23 '21 at 16:18

1 Answers1

0

You've only shown a single value, so it's difficult to know what kinds of other values might be returned from the function. However, based just on that one example, here's a type to describe it:

TS Playground

type Result = [
  number[],
  {
    acknowledged: boolean;
    modifiedCount: number;
    upsertedId: null; // really, this is probably (null | number) OR (null | string)
    upsertedCount: number;
    matchedCount: number;
  },
];
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • Thank you ! I solved like you said! btw the type of upsertedId is ObjectId, so I got ObjectId from Mongoos.types, here's my question. I heard ObjectId can be 'String' type, is It right ? – Emily Dec 23 '21 at 16:17
  • @Emily No, `ObjectId` is a class (see [line 24 here](https://unpkg.com/browse/mongodb@4.2.2/mongodb.d.ts) which points to [line 877 here](https://unpkg.com/browse/bson@4.6.0/bson.d.ts)), so you'd need to use that type: `ObjectId`. If this answers your question, feel free to mark it as such. – jsejcksn Dec 23 '21 at 16:25