And it represented a stark turnabout for Mr. Trump, who billed himself during the campaign 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.

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.