210 points · by mpweiher · 8y ago · 158 comments
Re: TypeScript:
> TypeScript challenges the status quo, claiming that lowering the cognitive overhead of using types is more important than type soundness. They argue that JavaScript programmers, their main audience, would find it easier to use TypeScript if they deviated from traditional norms.
Im not sure about the official mission statement, but as far as I understand, the purpose of their typesystem is to allow static description of the way existing JavaScript is typed, de facto, in the wild. This explains why e.g. literal strings are a type so you can do:
interface Eventor {
on('foo', FooHandler);
on('bar', BarHandler);
}
Not because it’s nice to have a type that "foo" satisfies and not "bar", but because there is actual code out there that does this, today. Same for structural typing (TypeScript would be absolute horror to interface with existing code without it). And, I assume, covariant arrays.TypeScript was not created in a void, as a fresh, new typesystem. It was created to formalise the way existing JavaScript was informally typed. It would have been nice to see a little reference to or acknowledgement of this.
Or an example of how this could have been achieved better; preserving type soundness.
Soundness means that every program that typechecks is valid. Completeness means that every valid program can be typed.
So basically typescripts type system doesn't match the language semantics so type checked programs may crash at runtime.
The engineering constraint is to ensure that the design and logic of the types themselves enable preservation-and-progress-validity to enforce meaningful semantic constraints. A sound and complete type system can still say things that aren't practically meaningful.
https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_sy...
I like this definition. Can someone link to an authoritative article that elaborates on this statement?
> Informally, a soundness theorem for a deductive system expresses that all provable sentences are true. Completeness states that all true sentences are provable.
https://en.wikipedia.org/wiki/Soundness#Relation_to_complete...
You could probably follow the references there to more authoritative sources.
That's in the line of Erlang's Dialyzer (one of the earliest "gradual typing" tools I know of), which also had to contend with actually being useful and being able to type actual usage patterns of existing years-old codebases..
Anecdotally, as an Elixir developer, I find Dialyzer to be pretty OK. Sometimes it misses things I think it should catch, but you quickly learn ways of structuring your code to help it more (not abusing macros, for one). We made a decision in the infancy of the code base to mandate typespecs for every function (both public and private) in the code base, and it has paid off in strides if for nothing else than documentation when you open a module you haven't touched in months. It catching bugs at CI time is a huge bonus. The error messages are... not great. I have it on hold right now, but I've got a branch for improving all the error messages in Elixir.
Many library authors are unfortunately not very diligent in speccing their programs. My first contribution to a dependency we use is often fixing their type specs to allow our code to type check. Some don't even bother putting in typespecs and Dialyzer gets upset because there's code paths it can't quite figure out, or even worse when one is wrong really deep in the middle. Seeing 80 errors in bright red because of a widely used utility function saying it returns a String.t() instead of an integer can be frustrating.
Re: CI, due to Dialyzer's persistent lookup table (PLTs) for all your app dependencies taking FOREVER to build from scratch, we had to do some trickery to get it cached as an artifact for future builds. But once that got working, CI got very snappy. It's really determined as a function of the triplet (erlang_version, elixir_version, the hashes of all your dependencies), so you can do things like create a docker image with a tag that is a function of that triplet.
For example, in lots of strongly typed languages when you make a sum type there's a constructor. haskell,
data Foo = Baz | Bar
or rust, enum Foo { Baz, Bar }
Baz and Bar are data constructors, they allow you to pattern match on them and make new values. In ts an equivalent sum type has to use a string/number refinement.
type Foo = { kind: "baz" } | { kind: "bar" }
This fits closer to js semantics and still allows sum types to be written. Unfortunately the pattern matching isn't anywhere near as good, but I applaud them for adding this to the language.
Instead, I now view type systems as a tool that can make tradeoffs to get the job done, in the same space as "IDE" or "test-driven design". With those it's easy to make statements about the specific programmer tradeoffs, such as "test-driven design means you spend more time writing tests but gives you more confidence about the results". With a given type system, you can evaluate it like "type system X lets you get autocomplete in your editor", or "type system Y catches the common error of Z".
Meanwhile if you only focus on soundness you end up with counterintuitive results like where Java is sound but still has NullPointerExceptions everywhere, or languages like Rust where whole data structures and algorithms are disallowed because you can't express their correctness to the compiler. (To be clear I appreciate exactly why Rust must do this, but again you can evaluate that tradeoff as "preserves memory safety without GC, disallows doubly-linked lists" rather than "is the type system 'correct'".)
One view that really opened my eyes on this Gilad Bracha's talk on pluggable and optional type systems: http://lambda-the-ultimate.org/node/1311 .
Nothing is disallowed in rust. You may need a specialized crate or a small 'unsafe' block to work beyond the compiler's ability to prove your code meets rust's guarantees, but that's not the same as inexpressible.
I'm not sure about that. C contains while loops. And every GOTO-computable programs should be expressible by WHILE-computable programs.
See (slide 21): http://ai.cs.unibas.ch/_files/teaching/fs16/theo/slides/theo...
The op didn't say "safe rust", that's my point.
Btw, Java is unsound; see 'Java and Scala's Type Systems are Unsound - Semantic Scholar' ( https://pdfs.semanticscholar.org/3705/c660290e98877f882cf908... )
Type system traditionalists think that static typing is all just about universal type checking, they ignore development tools, code completion, or useful but not absolute best effort type checking. Programming in Typescript really is nice because the type system helps even if it isn't perfect. It shows that there is a lot in the design space between "no static typing" and "sound static typing". Evidence Java and Scala being widely used even if they are technically unsound (where soundness itself is really a gradient). Type systems simply aren't black and white as the fundamentalists would claim.
You restrict the allowable subset of JavaScript in your codebase further to one you know is sound. This is pretty much the same strategy that `"use strict"` has, and literally no one complains about that, so it was never really about restricting JavaScript anyway, people just like to dump on soundness as being too un-pragmatic.
Sure, sometimes you really do need to work around the type system and express something you know can't go wrong. But it's always possible to contain it to a small, 'unsafe' part of the codebase! For example, Rust proves this quite nicely.
Not that this takes away from your larger point exactly, but Java+null is no longer a good example.
* It turns out Java accidentally turned out to be unsound in a really obscure corner case, unrelated to the nulls thing. https://hackernoon.com/java-is-unsound-28c84cb2b3f
Java has always had covariant arrays, which are not sound. Whether it was intentional or not is irrelevant to the question of 'does this language have a sound type system?'.
Here's some code which is syntactically legal in both TypeScript and Flow, but the languages disagree on whether a type error is present:
type T = { // Legal decl in Flow, illegal in TS
x: number;
[s: string]: boolean;
};
const m: T = { x: 1, xz: true };
m['xz'.substr(0, 1)] = true;
m.x.toFixed(); // Crashes
TypeScript is actually more sound than Flow in this example because it disallows the declaration of T in the first place. Flow allows this code and it fails due to a type error at runtime.Yet in JavaScript this is an extremely common pattern - an object bag where some known property keys have a certain type, but "all the others" have a different type. You can't represent this in a bolt-on type system without forcing the developer to jump through enormous hoops proving that any lookup key isn't one of the "known" keys. By enforcing soundness at all costs, you lose the expressiveness needed to ergonomically describe this object.
Since most people don't directly aim guns at their feet, the unsoundness here is unimportant in practice. This is one place where I think Flow made the right trade-off to be unsound for the sake of practical usability for a common pattern.
Coming from Haskell, the level of unsoundness in Flow is very grating, and I would honestly not recommend it over untyped JavaScript... It luls you into a false sense of confidence that the program is correct, without it actually being so.
TypeScript is a lot better in that area.
This line must only be accepted if a proof that 'xz'.substr(0, 1) != "x" is provided (for instance, inferred from a runtime check or encoded as a type) [obviously, that's impossible with that specific value]
While "unergonomic", code that doesn't do that is just broken and might for instance result in a security catastrophe if the key is attacker controlled.
If you have a sound type system, it's harder to write code but the compiler and IDE can infer useful invariants and give you guidance in return.
If you have no type system, you're on your own with error detection, but writing code may be a lot faster.
(Though I personally think a modern language with sound types and useful type inference can solve a lot of the tedium as well)
If you have an unsound type system you get the worst of both worlds: You have the cognitive overhead of a typed language but at the same time don't get any of the guarantees and invariants.
Yes, there are cases where you will not find an error until run time. Debugging this is identical to debugging that same error in Javascript, because you know you don't have guarantees from Typescript.
The more strict your type-system is the more things you can prove and thus understand about your program. But if you need to change your program it may no longer compile with the existing types. Does your type-system then make it easy to change your types so they reflect your new program?
Now assumably when you are developing a new program it is changing all the time. If you fix its types early doesn't it actually make it more work to create your program?
Once your application is done and works and is big it is essential that it is "typed" so that you can see what changes don't require changes in the types vs. what changes would require a lot of rewriting of the types all over the place.
I think the fact that many useful programs are written in dynamically typed languages speaks for this. Small programs don't need types.
Does this mean that optional typing is a good feature?
Furthermore, usually development uses type system as a tool, so it'd be hard to add typing when it's done. (I mean, usually functional doneness is checked or "asserted" in a large part through types, and unit/integration tests help with the rest.) So in this sense typing doesn't add more development time. It just makes problems a lot more explicit, so you know you're not done yet.
Yes. The type system in fact makes it easier to make this kind of change, because when I change one of my assumptions (e.g. I say "the input list to this function must always be non-empty") the compiler tells me exactly where I need to make a corresponding change.
> Now assumably when you are developing a new program it is changing all the time. If you fix its types early doesn't it actually make it more work to create your program?
Fixing the types early would indeed be a disaster, but why would you ever do that? Types are something that evolve and change as the program does, just like e.g. variable names.
It's basically like using and debugging C/C++ code, where it looks like there is a "type system" but in fact you are just arbitrarily manipulating a big byte array that contains all your data and the call stack (except with TypeScript it's a graph of untyped arrays and dictionaries instead).
In fact I do not know of any language that is actually safe at it's FFI boundaries. Rust isn't, Haskell isn't. You could get a value back from a C function that you were told would be allocated 64-bytes and actually it was only 32, so you'll have an overflow somewhere later. The Typescript / Javascript boundary is similar, though obviously not as dangerous.
I still like your analogy, as when things are down executing it is as you say just on big byte array, you should never try to map this array to the language manually though.
A simple example of python2 that would make developers brought up on a healthy diet of haskell cringe is this:
>>> for x in range(100): print type(1<<x)
And yet, pythonistas seem to mind nor bother.type(1 << x) is int for small x, but long for large x.
https://docs.python.org/2/library/stdtypes.html#numeric-type...
"Plain integers (also just called integers) are implemented using long in C, which gives them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value for the current platform, the minimum value is -sys.maxint - 1). Long integers have unlimited precision."
The distinction between plain and long integers is gone in Python 3.
- "Number", which would be the generic DWIM arithmetic type. In your example both x and the literals would be Number.
- Hyper-specified arithmetic types. Not just number of bits and signedness, but also overflow and trap behaviour. Less convenient to use - you can't easily add a "32bit signed wrap on overflow" to "16 bit unsigned saturate on overflow", but have the advantage that there is no unspecified behaviour. This also allows the user to make use of machine-provided saturate and overflow behaviour where present.
My idea is to let programmers specify various constraints they care about on numeric-typed variables, including min/max value.
Then the compiler has the freedom to choose any representation(s) it cares to that matches the constraints.
For complicated constraints that are difficult to prove at static-compilation time, some checks might be deferred until linktime (when static call contexts are available) or runtime.
C offers a fairly small choice of types to the programmer, certainly compared to one of the ML/Haskell style of language. It doesn't even have a proper "string" type!
C doesn't exactly allow mixed-type expressions, it just performs a lot of type coercion and reinterpretation. Which is another one of those things that trades safety for convenience in so many languages.
Type flexibility is responsible for most of the wtf type moments in Javascript: https://www.destroyallsoftware.com/talks/wat
The type systems we're talking about in the OP article are about proofs that can be made over the code before it is ever executed. Dynamic type systems make few claims here so they don't cause issues. What does cause issues is asserting something to be proven true, but having compositions in the language that make the assertion false.
dynamic -> dynamic -> dynamic
That's because that's how dynamic type systems work, from a static typing perspective. They defer typing until runtime. Properties of the code proven before execution aren't usually very interesting. << :: Integer -> Integer -> Integer
be good enough? << :: Int -> Int | Long -> Int | Long
<< :: Long -> Int | Long -> Long
? If you can express a dynamic type system at all, then this seems intuitive?Haskells approach to this keeps the constraint of soundness: https://youtu.be/re96UgMk6GQ?t=52m5s
The whole video is very interesting even if you know nothing about Haskell, but are just interested in language design in general.
To summarize the part of the video I just linked: Their approach so far has been to try and design the type system in such a way that you reduce programmer pain while not sacrificing soundness at all. It is a painful constraint for language designers, but it allows you to gradually add functionality to the type system from observing real world examples. The goal can be described as: Design a typesystem such that every working program can be typed in both a sound and correct way, while minimizing the amount of programs that can be typed, but are not working as intended.
In Languages like Haskell or completely dependently typed languages it would be morally wrong (in my opinion) to have an unsound type-system. Here the role of the types is different, you use types to compute types and need to trust the compiler in complicated situations that this is sound, just like you trust the compiler to do correct floating arithmetic. Checking the types per hand may be a real challenge, for example if your writing super polymorphic code. Sometimes you even have to prove that your code fits the type-signature (per induction etc.), here you want guarantees.
Not sure what the article is referring to here...
Java soundness issues like array covariance, final field mutability, unchecked generics casts, etc were definitely surprises to many users, but the Java language designers were well aware. They added runtime checking to make sure those soundness holes didn't cause the JVM to crash or violate the security guarantees.
Sure, there were some additional surprises, but I'm sure TypeScript has had many more. (Partly because the TypeScript type system is more complicated, but also because it's not important to get it 100% right -- JavaScript runtimes don't perform optimizations that rely on the soundness of TypeScript.)
Now, there are distinct disadvantages to unsound type systems, but that doesn't make them "wrong". I love Python and sometimes wish I could turn on a switch in the interpreter that made it statically typed, but there is no denying there is a freedom and (initial) productivity boost in ducktyping.
Other than that it really depends where. How bad unsoundness is depends on how sneaky the resulting errors are and how hard they are to debug.
[1] https://github.com/mobxjs/mobx-state-tree#thanks see tcomb
Types as „approximation of the result of a computation„ is also a nice and concise way to describe them, haven’t seen that definition before.
Soundness only provides a guarantee if you control when and how your code will be executed, and that's a tough constraint. To prove is not to forsee the future.
Which properties are you referring to? My understanding is that ES6 is back compatible and so that can't be case. There's "use strict" but that's a different kettle of fish; a pragma that changes runtime behaviour..
The most common JavaScript error I encounter is accessing fields of undefined objects.
Can't we simply have a type-system for JavaScript that only prohibits undefined field access and nothing else?
If we accept that the system will be unsound anyway, why not focus on the main benefit and throw all the baggage out?
Yes, but it's not easy for cultural reasons. In order to detect undefined field access you need to know what the fields are at compile time, which is to say, you need classes. Javascript's original design was based on prototypes, which have a fundamental "impedance mismatch" with classes. It's possible to layer classes on top of prototypes. That's actually not so hard, you can find a lot of user-level implementations of classes out there (e.g. https://github.com/neverblued/js-clos). But to make that part of the language so that compilers will be aware of it you'd have to get the community to agree on a design, and that is very challenging. But it's a political problem, not a technical one.
TypeScript has optional null checking if you want it. Given that it supports union types, null/undefined tracking fit nicely into the language.
(Downcasting from * in a gradual type system is analogous to how C lets you cast from void* to any pointer type implicitly, except that RTTI checks that the cast is safe.)
Neither unit testing nor contracts are verification tools.
After switching all my JavaScript Dev to ts a couple years ago, I cant imagine how I would get by without it.
- type inference
- structural types
- union and intersection types
- important: easy escape hatches such as trivial cast to `any` or the ability to write your own type definitions for almost any random piece of code including third party libs
Type purists may scoff at Typescript's type system, but it's there, it mostly works, it's very easy to get started with, it's reasonably fast. I would personally wish for exhaustive type checking, and I wouldn't be surprised if I get my wish sometime in the future.
Another rather pragmatically typed language is OCaml/ReasonML
It is possible to encode the semantics of exceptions such that a reasonable definition of soundness is still provable. See, for instance, Chapter 14 of Types and Programming Languages by Pierce.
That's not interesting. TypeScript did things in way Y, different from the usual way X, and some academics realize they get a free paper out of reimagining TypeScript doing X.
Let us synchronize ALL of the computers, while we’re at it.
Also, suddenly cryptography and computers are cool :)