Skip to content

Runtime type checking #1573

Closed
Closed

Description

@jednano

I request a runtime type checking system that perhaps looks something like this:

function square(x: number!) {
  return x * x;
}

Where the ! tells the compiler to generate a runtime type check for a number, something akin to tcomb.js.

Of course, this gets much more complicated with interfaces, but you get the idea.

Activity

  1. basarat commented on Dec 30, 2014

    @basarat
    Contributor

    Perhaps something more akin to google AtScript for consistency. Basically flag --rtts will cause emited JS to have rtts (runtime type system) checks inserted.

  2. jednano commented on Dec 30, 2014

    @jednano
    ContributorAuthor

    I'm suggesting, however, that you can optionally enable runtime type checking on some args and not others. Or, at least, skip type checking on private methods, optionally.

  3. RyanCavanaugh commented on Dec 30, 2014

    @RyanCavanaugh
    Member
  4. davidrapin commented on May 11, 2016

    @davidrapin

    For people like me coming here looking with high hopes, you might want to take a look at http://angular.github.io/assert/

  5. jeansson commented on Dec 7, 2016

    @jeansson

    Well, this can't be very complex to implement since you already have the infrastructure for type checking. At least you could expect to get injected type checking for primitive types when compiling with --debug, as mentioned in the other thread:

    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;
    }
    

    If this does not match your design goals, maybe you should change them?

  6. aluanhaddad commented on Dec 7, 2016

    @aluanhaddad
    Contributor

    Primitive TypeChecking is easy, and the results of doing it yourself guide type inference. If you expect to receive something other than the indicated type, perhaps you should not specify number.

  7. jeansson commented on Dec 7, 2016

    @jeansson

    I would expect to get a runtime error if a function receives eg a string instead of a number in runtime. That would really kill the flaws of working with JavaScript.

    Don't get me wrong, I love TypeScript, but I really hate JavaScript..

  8. aluanhaddad commented on Dec 7, 2016

    @aluanhaddad
    Contributor

    But, IMO, you need to learn to love JavaScript to fully take advantage of TypeScript.

  9. jednano commented on Dec 7, 2016

    @jednano
    ContributorAuthor

    Andreas (@jeansson) did you take a look at tcomb?

  10. jeansson commented on Dec 7, 2016

    @jeansson

    Well I think that is mission impossible for me. JavaScript is great for what is was made for, but for large complex systems built and maintained by a team I can't see how it could be a good modern option.

    jedmao Thank you, will have a look. But I still think it should be implemented in the TypeScript compiler (with a flag)

  11. jednano commented on Dec 7, 2016

    @jednano
    ContributorAuthor

    Ryan Cavanaugh (@RyanCavanaugh) it's been almost 2 years since this feature request was made and I'm wondering what it would take for the design goals to change or make an exception for this particular request? Now that the initial TypeScript roadmap is complete, perhaps we can entertain this idea?

    I think this proposed compiler flag would only make sense in development and staging environments, but it would serve as a great tool for debugging the application at runtime.

    Consider the scenario in which an API request is made and we expect the API response to adhere to a model (interface).

    interface Foo {
        bar: string;
    }
    
    function handleResponse(data: Foo) {
        return data;
    }

    Compiles to:

    const __Foo = {
        validate: (d) => {
            if (typeof d.bar !== 'string') {
                throw new TypeError('Foo.bar should be a string.');
            }
        }
    };
    
    function handleResponse(data) {
        Foo.validate(data);
        return data;
    }
    
    handleResponse({ bar: 'baz' }); // OK
    handleResponse({ bar: 42 }); // TypeError('Foo.bar should be a string.');

    Rather than getting some error about some foo prop being undefined, wouldn't it be more useful to know that the complex type that was defined as input didn't come back the way we expected?

  12. 68 remaining items

  13. wongjiahau commented on Apr 24, 2018

    @wongjiahau

    Anyway, will anyone support me if I'm going to implement this feature by forking this project?
    (I will seriously implement this if I get more than 20 reactions)

  14. tbillington commented on Apr 24, 2018

    @tbillington

    Apologies, my example used a non-any type when you specified casting any -> non-any.

    Still, it's a backwards-incompatible change which means you're fighting an uphill battle. That's why other people have suggested new syntax such as !.

  15. jednano commented on Apr 24, 2018

    @jednano
    ContributorAuthor

    WJH (@wongjiahau) I wouldn't necessarily want all "as" operators to create type checking code around it. I'd much rather be explicit with it with a simple ! on a case-by-case basis. Did you take a look at io-ts?

  16. wongjiahau commented on Apr 24, 2018

    @wongjiahau

    jedmao I did look at io-ts, I actually wanted to use it but it is not really natural when you have nested type.

    Trent (@tbillington) Ok now I understand your concern (of the backwards-compatibility).

    So, I guess the syntax should looks like this as suggested by jedmao?

    function square1(x: number!) { 
      // TS compiler will generate code that will assert the type is correct
      return x * x; 
    }
    
    function square2(x: number) {
      // TS compiler will not generate any type-assertion code
      return x*x; 
    }
    
    var apple: any = "123";
    square1(apple); // Compiler will not throw error, since the type of `apple` is `any`. 
                    // But this code will cause error to be thrown at runtime
    
    square2(apple); // Compiler will throw error 
    
    var banana = "123";
    square1(banana); // Compiler will generate error because you can't cast string to number by any means

    So, the ! operator is actually suppressing error that is related to casting from any to specific type.

    jedmao Trent (@tbillington) What do you think?

  17. jednano commented on Apr 24, 2018

    @jednano
    ContributorAuthor

    WJH (@wongjiahau) my opinion is that the compiler errors should be exactly as they are w/o change. The only difference is runtime. As such, I don't see how the ! operator would suppress any compiler errors at all.

    Let's take your example:

    function square1(x: number!) { 
      // TS compiler will generate code that will assert the type is correct
      return x * x; 
    }

    The TS compiler would simply emit something akin to the following:

    function square(x) {
        if (typeof x !== 'number') {
            throw new TypeError('Expected a number.');
        }
        return x * x;
    }

    Super easy with primitive types, but more complicated with interfaces and more complex types (but io-ts solves that issue).

    I just wish it were built into the compiler itself so we didn't have to do all this extra stuff. But it really is complex and requires a lot of thought behind it in order to do it right.

    Here's some other ideas I thought of recently:

    // First line of file
    const x: number! = 42; // compiler error: redundant type checking on a known type.
    const x: number = 42;
    const y: number! = x; // also redundant
    const x: number = 42;
    const y: string! = x; // compiler error: 
    const z: string! = x as any; // OK, but should it be?

    There's really a lot to think about here.

  18. wongjiahau commented on Apr 24, 2018

    @wongjiahau

    jedmao I understand what you say, but please allow me to clarify the error suppression with a typical example.

    Suppose you have the following code (using express.js) :

    interface Fruit {
      name: string,
      isTasty: boolean
    }
    
    app.post("/uploadFruit", (req, res) => {
      const newFruit = req.body; // Note that `req.body` has type of `any`
    
      // This line shouldn't throw compile error because we already tell the compiler 
      // to assert that newFruit is type of `Fruit` by adding the `!` operator
      saveFruit(newFruit); 
    });
    
    function saveFruit(newFruit: Fruit!) {
      // save the fruit into database
    }

    If that line of saveFruit(newFruit) will throw compilation error, then this runtime typechecking feature would be meaningless already.

    I hope you can understand what I'm trying to say.

    Moreover, I think that syntax A will be better than syntax B

    // syntax A 
    const apple!: string = "...";
    
    // syntax B
    const apple: string! = "...";

    This is because syntax A will be much more easier to be parsed, and it is also more consistent with the ?: operator.

    So you can read the !: operator as must be a.

  19. jednano commented on Apr 24, 2018

    @jednano
    ContributorAuthor

    WJH (@wongjiahau) I'm not suggesting that saveFruit(newFruit) should throw a compiler error, as req.body is of type any. Just like it won't throw a compiler error today, it shouldn't in the future. That's exactly what I said before. Current compiler errors should remain compiler errors, period.

    That said, I still don't see where any error is being "suppressed" as you say.

    I do kinda' like the !: operator idea. That would make forced union types a lot easier to read:

    function foo(x!: string | number) {}
  20. wongjiahau commented on Apr 24, 2018

    @wongjiahau

    jedmao Sorry for the misunderstanding, because I thought the compiler will throw error if we cast from any to a specific type, just realized it won't throw error.

    So, do you guys want to fork this project and implement this feature?

  21. jednano commented on Apr 24, 2018

    @jednano
    ContributorAuthor

    I think Microsoft would have to agree to accept a community PR for me to invest time in this. Also, I just don't have the bandwidth.

  22. wongjiahau commented on Apr 24, 2018

    @wongjiahau

    jedmao I'm actually thinking of forking it as another project (perhaps I'll call it Experimental-Typescript ? ).
    Because I notice there are a lot of potential pull request and issues that will not be implemented in this project, I'm thinking of merging them and implementing them.

  23. ccorcos commented on Apr 24, 2018

    @ccorcos

    Since we're talking a lot about validation of unsafe data, I think Phantom types are relevant:

    https://medium.com/@gcanti/phantom-types-with-flow-828aff73232b

    Currently, its not possible in Typescript.

  24. lkster commented on Apr 24, 2018

    @lkster

    I see some people made libraries for runtime checking but I would show another one (created by myself):
    https://github.com/ThaFog/Safetify
    Well i's not stricte for runtime type checking because the major difference comparing to others above is that it doesn't throw errors but simply replacing incorrect values with type-safe equivalents. So it's better to use in webservices, with taking data from API or so.

    However I'm planning to add features like optional errors throwing, global onError callbacks, constraints, json or function resolvers. then it would be more for runtime checking

  25. Ciantic commented on May 30, 2018

    @Ciantic

    Creator of Node.js seems to be working on similar project for TypeScript: https://github.com/ry/deno "A secure TypeScript runtime on V8"

  26. ccorcos commented on May 31, 2018

    @ccorcos

    Interesting. I checked out the repo -- still pretty unclear what it's for...

  27. locked and limited conversation to collaborators on Jul 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions