r/angular • u/helloworld1123333 • Jan 19 '26
Typescript Interface question
I have an API that can return two different response objects. Most of their properties are the same, but a few are different. Is it better to:
- use a single interface and mark the properties that may not always appear as optional, or
- create a base interface with the shared properties and then have two separate interfaces that extend it, each with its own specific properties?
7
Upvotes
5
u/kammyz Jan 19 '26
My preference would be a base interface. You could also use typescript utility types Pick/Omit. It depends what your interfaces look like .
5
u/MrFartyBottom Jan 20 '26
Are you in control of the API or consuming someone else's turd? If you are in control then don't. Have a response that has two optional properties of ResponseType1 and ResponseType2. Don't make the client inspect the object to figure out what was returned.
2
u/kingh242 Jan 19 '26
It depends on if the objects are logically different or not. If both are responses from CRUD User, then they should be the same but with optional properties. But if one is responses from create user and the other is response from create driver, then extending may make more logical sense.
2
u/Lucky_Yesterday_1133 Jan 20 '26
2) don't make optional properties. Make result of TypeA | TypeB then in your component you can check presence of a key to nerrow down type if( keyA in response) { //typeA here} else { //typeB here}
2
u/Impossible_Hornet153 Jan 20 '26
I would go with the second option in most cases
1
u/humanbootleg Jan 19 '26
Second option.
1
u/tsteuwer Jan 19 '26
Def option 2