`as` keyword in switch head

My idea is the ability to define block-scoped baviables in the switch head.

switch(object.with.deep.property as prop){
	default:
		use(prop)
}

This would work the same as creating a block variable just befor ethe switch statement.

{
	let prop = object.with.deep.property;
	switch(prop){
		/* ... */
	}
}

I’m only writing this informally, just to see where this discussion goes.

There is a (somewhat dormant, but seeing activity lately) proposal for declarations in conditionals i.e. if (let x = whatever); this seems like a pretty natural extension (if it used declaration syntax rather than a new keyword). The idea has come up in the issue tracker there.

3 Likes

Devin told me he was going to present declarations in conditionals at the next meeting (though I don’t see it on the agenda yet) so we’re probably going to be seeing more about that soon.

Update: It has been added to the agenda - add Declarations in Conditionals to 2025/11 agenda by dcrousso · Pull Request #1983 · tc39/agendas · GitHub

1 Like

I don’t see this proposal as particularly handy wrt what’s available today, which adds just a little annoyance. It would also introduce a TypeScript-like syntax which might be problematic for future evolutions of the language.

OTOH, @bakkot reminded of a nice and possibly safer alternative. Maybe it could match the spirit of OP’s proposal?