How much freedom do mathematics ph.d. students usually have in choosing a topic for their thesis in the U.S? I'm in a bit of a conundrum at the moment, since my real research interests (constructive type theory, proof theory, categorical logic) are only actively studied at a handful of places in the U.S, and for the most part those tend to be top schools.

Thus, I'm wondering if I don't get into one of said schools, would it still be possible for me to write my thesis in one of my areas of interest even if it is not directly related to any of the faculty's research interests? How much leeway do you have there?

For example, if I get into a school that has a good logic group, even if the research interests of the professors there is, say, more in set theory, would I still likely be able to do my thesis on type theory? What about at a school that doesn't even have a solid logic program?
There's a good deal of variation.  Sometimes students are assigned a very specific problem ("try to prove this conjecture"), sometimes given a slightly less concrete direction in a narrow range of a field, and some students do pick topics basically on their own.

Some of the variation is based on the individual professor, and some on the student - many, maybe most advisors are willing to give a fair amount of leeway to an exceptionally strong student, and will push more structure on a student who seems slightly weaker (weaker being quite relative).  (For example, I did my thesis in proof theory on a series of problems suggested by my advisor directly extending some of his previous work; my academic twin did a much more independent thesis in model theory on a topic my advisor had never directly worked in.)

So the answer is that you definitely can't count on a set theorist, or especially a non-logician, being willing to supervise a thesis in type theory unless you've communicated about that in advance, but it is sometimes done.  Also, people do occasionally have informal advisors, or even official advisors or co-advisors at other institutions; the logic community is small, so it is conceivable that if you get into a school with a good logic program and are really interested in a different area of logic you could nonetheless be at least partially supervised by someone at a different institution.  But, again, it's risky to count on this happening.