When we speak of comedy, we are really referring to a specific dramatic structure. While a comedy generally makes us laugh, and Twelfth Night certainly does have that effect in many scenes, being comic is really not all there is to a comedy. Specifically, comedies always surround the same topic or themes and end in similar ways. More specifically, a huge element in especially a Shakespearean comedy is that it surrounds the topic of family and the tension that must lead to a resolution also surrounds a familial situation. Since family is a huge topic in comedies, the plays always end in marriage, and more importantly, "marriage is celebrated ... as a social occasion" ("Comedy: An Introduction"). Shakespeare's comedies also always involve stock characters, which are character types seen repeatedly within a specific genre. Stock characters you will find in Shakespeare's comedies are the heroine's parents or guardians, clever wives or servants, and especially clowns, and fools ("Shakespeare's Plays: Comedy"). Since Twelfth Night certainly ends in marriage and contains stock characters, like Maria who is a clever servant and Feste who is a fool, we certainly know that the play fits in with the dramatic structure referred to as a comedy.
However, comedies, especially Shakespeare's comedies, aren't always very simple. Not only do they surround the topic of family, they surround the topic of society at large. Hence, often within one of Shakespeare's comedies you will also find characters who are social misfits and at the end of the play are ostracized because they are "so lost or misguided that they cannot be accommodated or restored to society" ("Shakespeare's Plays: Comedy"). Malvolio fits the description of this sort of misguided character. He is proven to be so arrogant and clash so much with the other characters that he leaves their society, vowing, "I'll be revenged on the whole pack of you" (V.i.391). Because the play ends with Malvolio having been severely mistreated and leaving the rest of society in the play, the play ends on a sadder note than would be expected, even though the characters will be marrying in the end. The play further ends on a sadder note when we get to Feste's song, which describes the harshness of life and especially the fact that foolishness, like Malvolio's foolishness as well as the foolish way in he was treated, is a primary contributing factor to the harsh reality of life, as we see in his first few lines:
When that I was and a little tiny boy,
With hey, ho, the wind and the rain,
A foolish thing was but a toy,
For the rain it raineth every day. (401-04)
Hence we see that even though comedies, especially Shakespeare's comedies, can deal with some weighty subjects and themes, if they follow a specific structure, they are most definitely considered comedies as opposed to any other dramatic structure, like histories or tragedies.