TypeScript: how to create an interface where one of two properties is required?
Hello everyone! I'm writing a TypeScript application for order processing. I have an interface for a user who can be either registered (and then has `userId`) or a guest (and then has `guestToken`). But the main thing is that the user must have exactly one of these two fields, not both at once and not none.\n\nHere's how I tried to do it:\n\n```typescript\ninterface User {\n name: string;\n email: string;\n userId?: number;\n guestToken?: string;\n}\n```\n\nBut the problem is that TypeScript allows creating an object where both fields are missing, or both are present at the same time. For example:\n\n```typescript\nconst user1: User = { name: "Anna", email: "a@mail.ru" }; // No userId or guestToken — no error\nconst user2: User = { name: "Ivan", email:
No answers yet.
Log in to leave an answer
Blogs