-
Notifications
You must be signed in to change notification settings - Fork 1.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Casting to a subtype / force cast #1898
Comments
Try this: function foo(e_: any) {
const e: MouseEvent = e_;
} In general you can use this pattern for force-casting: const foo: number = (('foo': any): number) |
That's pretty brutal, but the second option works. We really could use some official syntax for this. |
I run into this all the time, it would be nice if there was something like |
Yeah, this would be hugely useful for e.g. screwing with |
IMO it's a good thing that it looks ugly and stands out |
|
@vkurchatkin I see where you're coming from but it's so common, especially when dealing with React that it does warrant a suitably scarily named shortcut IMHO. In my experience people just use |
Well, maybe. For me |
Swift has a beautiful syntax for the case where you just want to assume a value is non-null, using a bang to 'unwrap' an unsafe value, like Like if you have a This lends itself to much shorter inline code like The bang syntax indicates the circumvention of type-safety in specific cases where you are positive a value will exist so it's naturally self-documenting. Personally I'd love a feature like that in Flow since currently I'm writing big null checks after getting values I am certain will not return null. |
I use a function like this: function unwrap<T>(val: ?T): T {
if (val == undefined) throw new Error();
return val;
} |
Closing since the initial issue has been resolved. You can cast through any 👍 The correct solution is to fix our libdefs. We’d be happy to accept PRs 😊 |
I agree with @mosesoak 100%. Why not make maybe-unwrapping more concise? 😕 |
When the built-in declarations are incorrect and/or missing functions, it would be really helpful to be able to force a cast. For example:
This throws the errors:
I need a way to cast
Event
toMouseEvent
, as I know (but Flow does not) that the return type ofdocument.createEvent('MouseEvents')
isMouseEvent
.This is also related to #396 as this would be fixable with an easy way to extend built-in types.
The text was updated successfully, but these errors were encountered: