Type systems could do stuff like that many, many years ago. I'm glad that you like these ideas, but let me assure you that TypeScript is far from pushing "what type systems can do".
FWIW, I didn't see any condescension there. I got more of a "Oh, you ain't seen nothin' yet!" vibe from it. Obviously, YMMV.
EDIT: Words
Anyway, I'm sure that I don't care if an unknown language pioneered something. The language that makes good features popular is the better one.
Gradual typing isn't exactly a TypeScript invention: Typed Racket is gradually typed, has unions and intersections (which in turn date from further back than TR), refinement types, occurrence types, and even comes with a guarantee that typed code won't violate contracts. If the Racket runtime detects a contract violation, blame will always be assigned to untyped code. TR does more than TS does, and it was designed and implemented earlier.
> It sounded a bit condescending to me.
I didn't read k_bx's comment as belittlement of TypeScript: anything that makes JavaScript better is obviously a good thing! (Since we can't get rid of it.) But, as a matter of fact, TypeScript isn't pushing “what types can do”.
TypeScript is a pretty bad type system, but compared to Java and other mainstream ones, it looks like it "pushes the envelop".
Because of this, we're stuck with an half baked, crappy type system designed for mass consumption, and people adopt it with a round of applause.
That's no excuse to me an ass in response to your post...but it's part of why you'll see answers like that.
I astouned what some people read into a perfectly reasonable critique...
What about PureScript, it's way beyond TypeScript and still compiles and interacts with JavaScript.
Just to be clear, this isn't meant as criticism, since I absolutely love how Haskell (and now PureScript too!) exploit algebraic structures to make code more reusable and robust. But the contrast between “can express fancy structures precisely” and “doesn't have precise arithmetic” is very amusing.
That people are actually using TypeScript could be the difference here.
As a side node, the FlowType system for JavaScript has had these features for over a year now, while TypeScript 2 is still in beta. These are the exact features which made us decide to go for FlowType instead of TypeScript 6 months ago. Happy to see that these two type systems now converge.
29 days ago somebody posted an unofficial Windows binary: https://github.com/facebook/flow/issues/6#issuecomment-22989...
function myFunction(x) {
if (x === null) {
return;
}
console.log(x + 1); // x is now a number
}
Edit: Or is this example being used to show that TypeScript now support multiple types including null in the parameter?I assumed that such feature would be available by default.
y = myFunction(1); // y = 2
y = myFunction("1"); // y = "11"
the ts version wouldn't allow you to compile myFunction("1")
The point of the example is that Typescript recently added support for non-null types, but is flexible enough to analyze where types have been further restricted by an early function return.
This thread, with people like you that seem to get it, is definitely making me want to try typescript.
function uhoh (x:string|number) {
if (typeof x === 'string') {
return x.length
} else {
return 'bar'
}
}
const a = uhoh('foo') //= string | number
const b = uhoh(3) //= string | number function uhoh (x:string|number) {
if (typeof x === 'string') {
return x.length
} else {
return 'bar'
}
}
function uhoh (x:string): number;
function uhoh (x:number): string;
const a = uhoh('foo') //= number
const b = uhoh(3) //= string uhoh : ((x : string) => number) & ((x : number) => string)
And get what you expect: const a = uhoh('foo') // : number
const b = uhoh(3) // : stringerror TS2354: No best common type exists among return expressions.
So at least it detects the problem. However the type inference algorithm should arguably return a union type here.
I find it good practice to always specify the return type of functions anyway. Then it will pick up cases where you return a type you didn't intend to; instead of just using a more general type it will tell you about the inconsistency.
I suppose the reasoning is that, when adding types to js, this is exactly the kind of bad behaviour you want to catch. But I'm not sure, perhaps there are just technical implications for not inferring union return types.
And the actual type of the const won't be `string | number` -- it will be `any`.
MaulingMonkey[1] has the right idea, though.
> if (a instanceOf SomeClass && a.someGetterOnSomeClassNotAvailableOnTheStaticTypeOfa != null)
Which is pretty awesome because it means you don't have to pollute your code with unnecessary casts.
fun myFunction(x: Number?) {
if (x == null) return;
print(x + 1);
}
if you don't check for null first the compiler warns.You can also do:
x?.let {notNullX -> print(notNullX + 1)}
or print((x ?: 4) + 1)
https://kotlinlang.org/docs/reference/null-safety.htmlIt really is an awesome language. Especially the delegated properties are wonderful. I use them to fill javascript-state for redux/react-native.
function second(y: number) {
return y + 3;
}
And you call second(x) from myFunction, the compiler complains if you haven't put the if() ensuring that null cannot pass to second()?But it goes further than that. TypeScript 2 adds control flow analysis, so adding to the top of a function that accepts a string or an array:
if (typeof someVarThatCanBeStringOrArrayOfStrings === "string") { // turn string into array }
any code below it can safely assume that the variable is string[], as well as the rest of the code that calls this function if this variable is returned.
(correct me if I'm wrong, y'all)
In your example, the JS interpreter will not throw an error when one provides a number (for example). Your code could break things. But why would this happen?
It's completely unrelated to TypeScript.
A number could be provided by the data, which in all likelihood is JSON from the network (eg: HTTP request or message queue body). Strongly typed languages will give you strongly typed data to protect you from this, but a dynamic language like JS doesn't afford you the same protection.
TypeScript doesn't mitigate this issue -- nor could it. TypeScript ensures your plumbing fits together, not that the sludge flowing through it won't cause a mess.
A strongly typed language will throw an exception before unexpected behavior can occur, JS on the other-hand will attempt to continue. It rarely happens, but since it does you can't say it safely works properly.
If a strongly typed language receives data that is malformed, wouldn't the same problem arise? Isn't it always the case that you only have control over your own plumbing, and put up defenses to deal with external input?
(I have little experience with strongly typed languages, so I'm really interested to understand this a bit better)
TypeScript 2.0 goes beyond that and begins to push the envelope on what type systems can do. Recently I've been loving the combination of discriminated union types and nullable types. It means that you can have code like this:
The argument to the function is x, which is either number or null (that's what number | null means). But the if statement ensures it's not null by exiting the function, so by the time you get to the log TypeScript has (correctly) set the type of x to be just number!The types match up exactly with how you'd write the Javascript code. It's awesome and it just works.