mockdeep / typewiz

Automatically discover and add missing types in your TypeScript code
https://medium.com/@urish/manual-typing-is-no-fun-introducing-typewiz-58e3e8813f4c
1.1k stars 46 forks source link

Synergy with runtime typechecking? #91

Closed zxti closed 5 years ago

zxti commented 5 years ago

I'm not sure if this is something you're remotely interested in or if there really is not much overlap here, but it seems like you have built a powerful general platform for runtime type instrumentation that can be applied in other ways—one immediate application that comes to mind is runtime verification of Typescript types.

While adding types to my project, I of course made many mistakes. If I simply remove the types I added, Typewiz is perfectly capable of supplying precise types—verifying types seems even easier.

I did just now come across one other project that has this rough goal, which may be of interest:

https://github.com/fabiandev/ts-runtime

Anyway, such a tool could be a handy complement to Typescript, since runtime features are outside its goals. And it would be something that could be a permanent tool addition, rather than something you're "passing through," which is what Typewiz feels more like (you can be "done" converting a codebase from JS to TS).

A tool like this could further render obsolete many assertion-style coding practices used in TS codebases today. For instance, I commonly use functions like the following:

function checkNotNull<T>(x: T | undefined | null): T {
  if (x === undefined || x === null) {
    throw new Error();
  }
  return x;
}

function checkInstance<T>(x: any, klass: Function): T {
  if (!(x instanceof klass)) {
    throw new Error();
  }
  return x as T;
}

etc.

These still are useful at system/interface boundaries, but where they are used more as dev-time assertions, these can be omitted entirely in favor of simple TS expressions like:

x! // rather than checkNotNull(x)
x as Class // rather than checkInstance<Class>(x, Class)

Anyway, just one thought I'd throw out there. I actually feel this must not even necessarily be the most compelling application of what you have, but I haven't thought much about it.

urish commented 5 years ago

This is an interesting direction indeed - see some related discussion in #30, #74.

Personally, I don't use any kind of runtime type assertions, so I have no experience with this. I did take a quick look at ts-runtime, and it seems like it does the trick pretty well. Do you use ts-runtime in your project?

zxti commented 5 years ago

Ah, interesting related discussions. Not yet as I'm still just adding types to my project (with the help of Typewiz!), but once types are in, it would make sense for me to look into this, to catch the mistakes I've made from adding types. I don't know how much overhead etc. it would add yet, though.