Proposal: Run-time Type Checks
srijs opened this issue · 4 comments
Hi there!
I am writing a lot of code in an environment where JavaScript and TypeScript freely interact with each other. One thing that we continue to run into is where we would write a function in TypeScript, say:
export function add(x: number, y: number): number {
return x + y;
}
This function is callable from JavaScript, where we're allowed to do things like:
add('abc', undefined)
This has lead us to introduce type checks for all exported functions in TypeScript, although they really feel verbose in a typed language.
export function add(x: number, y: number): number {
if (typeof x !== 'number' || typeof y !== 'number') {
throw new TypeError('x and y need to be numbers');
}
return x + y;
}
My idea is to provide an optional flag, say --insertRuntimeTypeChecks
, that makes the compiler insert these kinds of checks for function arguments.
The feature will probably be a bit more complicated when thinking about structural types, etc., especially in interplay with classes (it is my understanding that classes are type-checked structurally, not nominally, is that correct?).
But even having it only for primitive types (checking for object
, string
, number
, etc.) could provide a lot of benefits for those of us who write code that interacts with JavaScript, especially should #7140 land, to spare us from manually writing if (x === null) ...
.
I'd be interested in giving implementing this a shot, if there's interest from the maintainers.
I would say a compiler flag is too broad, and a decorator like @runtimeChecked function() {...}
would be much less intrusive - also, in this way we also get a place to specify the error message, and whether we allow to remove the typecheck if the compiler decides it is statically not needed.
...also, I think you could write said decorator yourself, with type guard functions, except that you will likwly have to specify types explicitly, e.g @runtimeChecked<number,number,number> function(){ ...}
Babel provides something along the lines of this request: https://github.com/codemix/babel-plugin-typecheck (linked from the same request for Flow: facebook/flow#897 )
Duplicate of #1573