You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For some reason I thought TypeScript already had a feature of type narrowing via constructor, and it sort of does, but today I tried:
constimages=this.productImages// this is string | Map<string, string>if(images.constructor===String){returnimages// TypeScript correctly identifies this as a string}returnimages.has(ImageConstants.Large).// TS error: Property 'has' does not exist on type 'string | Map<string, string>'
? images.get(ImageConstants.Large)
: images.get(ImageConstants.Medium)
I take it that's because there are edge cases where a string can have a constructor from something other than String, but it would be nice to be able to tell TypeScript that that's never going to happen.
+1 as I am creating a simple game where spells or hands can be thrown.
I am trying to identify the type of action and adding "type":"meele" to a class feels inadequate if I could use constructor with switch case.
Activity
glebm commentedon Oct 21, 2017
At first I though this was because
T.constructoris not of typeT(#3841), but looks like that's not the only issue:glebm commentedon Oct 27, 2017
Ryan Cavanaugh (@RyanCavanaugh) What kind of feedback is this awaiting?
mhegazy commentedon Oct 27, 2017
We would like to get hear more user requests in favor of supporting this features
ExE-Boss commentedon Aug 28, 2020
You need to add
breakstatements:function f(x: A | B) { switch (x.constructor) { case A: x.a(); + break; case B: x.b(); + break; } }Also, another issue is that TypeScript doesn’t do narrowing using
===on objects.karol-majewski commentedon Nov 3, 2020
I needed it a few times now. A use case from today: applying a strategy based on a runtime type.
TypeScript Playground
Such code is both concise and very readable. Wouldn't it be nice if elegance was complemented with type safety? 😢
murbanowicz commentedon Apr 13, 2021
Is there any chance it will be fixed?
ukstv commentedon Sep 7, 2022
Oh, I can add +1 to this feature request. Definitely needed in reactive programming.
matthew-dean commentedon May 5, 2023
For some reason I thought TypeScript already had a feature of type narrowing via constructor, and it sort of does, but today I tried:
I take it that's because there are edge cases where a string can have a constructor from something other than
String, but it would be nice to be able to tell TypeScript that that's never going to happen.mackuba commentedon May 20, 2024
Bumping this up, this still doesn't seem to work…
Lukortech commentedon Jan 25, 2025
+1 as I am creating a simple game where spells or hands can be thrown.
I am trying to identify the type of action and adding "type":"meele" to a class feels inadequate if I could use
constructorwith switch case.