In housing, there are plenty of expressions which refer to different houses depending on their size, type or function.
In North America and Australia, townhouse refers to a type of home with two or three floors and a common wall with the adjacent house. Contrary to the condominium ownership, in which the owner owns only the airspace between the walls, ceiling and floor, townhouse owner owns the actual structure as well. In British English, townhouse originally referred to city residence of a noble person in opposition to their country residence.
Contrary to a townhouse, a duplex has two apartments with separate entrances. A duplex can refer to a two story house with a separate apartment on each floor, or two apartments on the same floor separated by a common wall.
In conclusion, the difference between the two expressions lies within the number of owners. A townhouse usually has only one owner, whereas a duplex has two.