-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 !

5
  • 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 Commented Dec 23, 2021 at 1: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. Commented Dec 23, 2021 at 1: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. Commented Dec 23, 2021 at 2:08
  • Seen this? stackoverflow.com/questions/25469244/… Commented Dec 23, 2021 at 2:33
  • Yep I've solved it! Thanks Dai Commented Dec 23, 2021 at 16:18

1 Answer 1

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;
  },
];
Sign up to request clarification or add additional context in comments.

2 Comments

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 No, ObjectId is a class (see line 24 here which points to line 877 here), so you'd need to use that type: ObjectId. If this answers your question, feel free to mark it as such.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.