3 ms·
Yes, this is the effective difference between Typescript and typecasting in most other languages. Typescript, since it compiled to js, doesn't know the runtime
by slackingoff2017 9y ago
Yes, this is the effective difference between Typescript and typecasting in most other languages. Typescript, since it compiled to js, doesn't know the runtime type so it can't use reflection to make sure casts are valid. It just takes your word for it. If the cast isn't always correct prepare for a world of pain trying to track it down instead of getting an exception on casting failure
- smaddox 9y agoI encountered this the other day, while playing with typescript for the first time. Is there a good solution, such as a utility function that does a runtime check before casting? I suppose I could write one for each type cast, but it seems like I shouldn't need to.
- slackingoff2017 9y agoKind of maybe. See http://blog.wolksoftware.com/decorators-reflection-javascript-typescript http://blog.wolksoftware.com/decorators-reflection-javascrip... for use of experimental reflection API. Note that Typescript tries to follow JS to remain a superset that easily compiles down, and the metadata API is currently a stage II Ecma proposal so it's marked experimental. It should be fairly easy to build a types casting method using that.
- styfle 9y agoYes, a runtime check in TypeScript is the same as a runtime check in JavaScript. function inc(n) { if (typeof n === 'number') { return n + 1 } throw new Error('Parameter n is not a number'); } If you wanted to actually runtime check all types (probably not advised) you could parse the type annotations. Or you could define your types using something like JSON Schema and validate against that. https://github.com/bcherny/json-schema-to-typescript https://github.com/bcherny/json-schema-to-typescript https://github.com/YousefED/typescript-json-schema https://github.com/YousefED/typescript-json-schema
- slackingoff2017 9y agoI'm sorry to say but... This check won't help with accidental incorrect casts. Typeof in typescript is a pass through for the JavaScript function, so it only returns what the JS version does. A check for a string or number will work, but a check against a typescript object or something complex like a union type will just return 'Object'
- spion 9y agoYou can use a tslint rule to block casts. That way you will only be able to use type guards to change the type of something.