How to specify a specific string in a TypeScript interface (literal type)
Hi everyone! I just started learning TypeScript and ran into a problem. I need to create an interface for an object that has a `status` field. This field should accept strictly defined values, for example: `"active"`, `"inactive"` or `"pending"`. If you try to assign any other string, a compilation error should occur.\n\nI tried doing this:\n\n```typescript\ninterface UserStatus {\n status: string;\n}\n```\n\nBut this doesn't work because `string` allows any strings. I want TS to check that the value of the `status` field is one of three possible strings.\n\nI tried using `enum`, but I was told it can be done simpler — using literal types. How do I properly describe such an interface? And is it possible to make the IDE suggest possible options while typing?
No answers yet.
Log in to leave an answer
Blogs
Asynchronous Programming in Swift: Complete Guide with Examples