-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
type-safe cast #3193
Comments
function cast<T>(instance: T, ctor: { new(...args: any[]): T }): T {
if (instance instanceof ctor) return instance;
throw new Error('type cast exception');
} The reason there's no built-in operation for this is that it's not possible at runtime to detect many things (for example, |
I think you're just saying that instanceof is broken on primitives in JavaScript. But why can't we have a cast operation that is consistent with the semantics of instanceof? Which would work as expected on classes. |
Can you post an example of how you'd want that to work? |
Like I said:
I find I keep repeating that boilerplate which mimics a "normal" safe cast operation. |
For example, let's say you wrote the following: interface Foo {
(x: string): void;
}
var j: any = whatever;
var x = cast<Foo>(j); /* write the JavaScript you would expect to be emitted here */ The |
OK. I'd expect that to be an error, but that certainly would be annoying for a supposed cast expression.
test.ts(9,19): error TS2345: Argument of type 'number | A' is not assignable to parameter of type 'A'. |
This works: function cast<T>(instance, ctor: { new(...args: any[]): T }): T { // instance should be "any"
if (instance instanceof ctor) return instance;
throw new Error('type cast exception');
}
class A {
foo: number;
}
var x: A | number = new A();
var y = cast(x, A); // type param is not required |
Thanks @duanyao that's exactly what I was looking for! |
There doesn't seem to be a safe cast in Typescript. (<T> x) does no dynamic check. This is a very common need and is provided in every other optionally and gradually typed language I know of. What is needed is something like:
except that doesn't compile. Is there an alternative solution I'm missing?
The text was updated successfully, but these errors were encountered: