âThatâs something that the Department of Defense and the White House will have to work together as implementation takes place and is done so lawfully,â Sarah Huckabee Sanders, the White House press secretary, said.
Still, the announcement thrilled elements of Mr. Trumpâs base, who have been dismayed to see the president break so bitterly in recent days with Attorney General Jeff Sessions, a hard-line conservative.
Civil rights and transgender advocacy groups denounced the policy, with some vowing to challenge it in court. Pentagon officials expressed dismay that the presidentâs tweets, blasted out before they could consider how to make the change, could open them to lawsuits.
The ban would reverse the gradual transformation of the military under President Barack Obama, whose administration announced last year that transgender people could serve openly in the military. Mr. Obamaâs defense secretary, Ashton B. Carter, also opened all combat roles to women and appointed the first openly gay Army secretary.
And it represented a stark turnabout from Mr. Trumpâs rhetoric during his campaign, when he billed himself as an ally of gay, lesbian, bisexual and transgender people.
The president, Ms. Sanders said, had concluded that allowing transgender people to serve openly âerodes military readiness and unit cohesion, and made the decision based on that.â
Mr. Mattis, who was on vacation, was silent on the new policy. People close to the defense secretary said he was appalled that Mr. Trump chose to unveil his decision in tweets, in part because of the message they sent to transgender active-duty service members, including those deployed overseas, that they were suddenly no longer welcome.
The policy would affect only a small portion of the approximately 1.3 million active-duty members of the military. Some 2,000 to 11,000 active-duty troops are transgender, according to a 2016 RAND Corporation study commissioned by the Pentagon, though estimates of the number of transgender service members have varied widely, and are sometimes as high as 15,000.
The study found that allowing transgender people to serve openly in the military would âhave minimal impact on readiness and health care costsâ for the Pentagon. It estimated that health care costs would rise $2.4 million to $8.4 million a year, representing an infinitesimal 0.04 to 0.13 percent increase in spending. Citing research into other countries that allow transgender people to serve, the study projected âlittle or no impact on unit cohesion, operational effectiveness or readinessâ in the United States.
The announcement came amid the debate on Capitol Hill over the Obama-era practice of requiring the Pentagon to pay for medical treatment related to gender transition. Representative Vicky Hartzler, Republican of Missouri, has proposed an amendment to the spending bill that would bar the Pentagon from spending money on transition surgery or related hormone therapy, and other Republicans have pressed for similar provisions.
Mr. Mattis had worked behind the scenes to keep such language out of legislation, quietly lobbying Republican lawmakers not to attach the prohibitions, according to congressional and defense officials.
But Mr. Trump was concerned that the transgender medical care issue could imperil the security spending measure, which also contains $1.6 billion for the border wall that he has championed, and wanted to resolve the dispute cleanly and straightforwardly, according to a person familiar with his thinking, who insisted on anonymity to describe it. That prompted his ban.
The presidentâs decision shocked even Republican congressional leaders, who were aware Mr. Trump was looking into whether taxpayer money should be spent on medical procedures for transgender service members, but had not expected him to go so far as to bar transgender people from serving altogether.
Mr. Trump and Republican lawmakers had come under pressure from Tony Perkins, the president of the Family Research Council, a leading Christian conservative group, and an ally of Mr. Trump. Mr. Perkins opposed the bill over spending on transgender medical costs and lobbied lawmakers to do the same.
âGrant repentance to President Trump and Secretary Mattis for even considering to keep this wicked policy in place,â the Family Research Council said in one of its daily prayers last week. âGrant them understanding, courage and willpower to stand up to the forces of darkness that gave birth to it and wholly to repeal it.â
Opponents of allowing openly transgender service members had raised a number of concerns, including what they said was the questionable psychological fitness of those troops and the cost the military would bear for their medical treatment, potentially including gender reassignment procedures. They said the military was being used for social experimentation at the expense of national security.
âThis was Ash Carter on his way out the door pulling the pin on a cultural grenade,â Mr. Perkins said on Wednesday. âOur military leaders are saying this doesnât help make us a better fighting force; itâs a distraction; itâs taking up limited resources.â
Mr. Carter objected to the decision, for its effect on the military and on those considering joining.
âTo choose service members on other grounds than military qualifications is social policy and has no place in our military,â he said in a statement. âThere are already transgender individuals who are serving capably and honorably. This action would also send the wrong signal to a younger generation thinking about military service.â
While some conservative lawmakers, including Ms. Hartzler, praised Mr. Trump, the president drew bipartisan condemnation on Capitol Hill and outrage from civil rights and transgender advocacy groups.
âThere is no reason to force service members who are able to fight, train and deploy to leave the military â regardless of their gender identity,â said Senator John McCain, Republican of Arizona and the chairman of the Senate Armed Services Committee.
He called Mr. Trumpâs move âyet another example of why major policy announcements should not be made via Twitter.â
Senator Jack Reed, Democrat of Rhode Island and the ranking member of the Armed Services Committee, noted the irony of Mr. Trumpâs announcing the ban on the anniversary of President Harry Trumanâs order to desegregate the military. âPresident Trump is choosing to retreat in the march toward equality,â he said.
In June, the administration delayed by six months a decision on whether to allow transgender recruits to join the military. At the time, Mr. Mattis said the delay would give military leaders a chance to review the shiftâs potential impact. Mr. Mattisâs decision was seen as a pause to âfinesseâ the issue, one official said, not a prelude to an outright ban.
The delay on recruits âwas largely based on a disagreement on the science of how mental health care and hormone therapy for transgender individuals would help solve the medical issues that are associated with gender dysphoria,â Gen. Paul Selva, the vice chairman of the Joint Chiefs of Staff, said during his reconfirmation hearing last week.
âI am an advocate of every qualified person who can meet the physical standards to serve in our uniformed services to be able to do so,â he said.
Mr. Mattis, a retired Marine, has not been a major proponent of allowing transgender people to serve in the military, in part because medical accommodations, including hormone injections, could open the Defense Department to claims from other people not allowed to serve, like Type 1 diabetics, who also need regular injections.
But Mr. Mattis and the Pentagonâs military leadership all seemed to have accepted that transgender people already serving in the military would be allowed to remain. A senior adviser to Mr. Mattis, Sally Donnelly, represented the Palm Center, an organization that advocated on behalf of the L.G.B.T. community in the military during the debate that led up to the Obama administrationâs decision to allow transgender people to serve, defense officials said.
Mr. Trumpâs abrupt decision is likely to end up in court; OutServe-SLDN, a nonprofit group that represents gay, lesbian, bisexual and transgender people in the military, immediately vowed to sue.
âWe have transgender individuals who serve in elite SEAL teams, who are working in a time of war to defend our country, and now youâre going to kick them out?â Matthew F. Thorn, executive director of OutServe, said in an interview.
Lt. Commander Blake Dremann, a Navy supply corps officer who is transgender, said he found out his job was in danger when he turned on CNN on Wednesday morning. Commander Dremann came out as transgender to his commanders in 2015, and said they had been supportive of him.
He refused to criticize Mr. Trump â âwe donât criticize our commander in chief,â he said â but said the policy shift âis singling out a specific population in the military, who had been assured we were doing everything appropriate to continue our honorable service.â
He added: âAnd I will continue to do so, until the military tells me to hang up my boots.â
An earlier version of this article misstated the president’s tweet, saying he would not “allow or accept” transgender people in the military. He tweeted he would not “accept or allow” transgender people in the military. The error was also sent in an alert.