Hacker News new | past | comments | ask | show | jobs | submit login
TypeScript 2.3 (microsoft.com)
366 points by DanRosenwasser on April 27, 2017 | hide | past | favorite | 116 comments



Author of vetur[0] here, glad to see it getting featured :-)

Started this plugin last October to provide better editor support for Vue single file component, now vetur has support for embedded IntelliSense / error-checking / syntax-highlighting / emmet / snippet / linting / formatting. By embedded support I mean each feature is available for at least html/css/js, some features are also available for scss/less/ts/etc.

@sandersn from TS team has been really helpful in helping me integrating TS's Language Server to powers the advanced IntelliSense in vetur. As vue / vuex / vue-router now comes with type definitions, you get awesome auto completion such as [1] and [2].

Now that IntelliSense in js/ts sections is almost complete, vetur's next step is to use TS's Language Server to extract info from Vue SFC's script part to power IntelliSense in templates, such as prompting a list of `props` for `v-if`, and prompting a list of `methods` for `@click`.

Give it a try and let me know any bugs or features you want to see!

[0]: https://github.com/octref/vetur [1]: https://twitter.com/octref/status/854812632142024705 [2]: https://twitter.com/octref/status/857350977581723648


Vetur is awesome! Thanks octref for your continued work and support :)

The "feature" I'd like to see most is a "perfect setup" guide (or maybe auto-detecting-and-helping logic?) detailing what's required to get all the features working. Currently for example I don't get HTML/CSS formatting, even though it was featured in 0.6.0 changelog, but I have no idea why :-/ . Got this feeling a few times with vetur as well as other linters: things work, but maybe not 100%, and it can be opaque to dig deeper: is it due to vscode misconfiguration? vetur misconfiguration? missing tooling? I don't know.

EDIT: these TS-dependent auto-completions look fantastic. I'm planning to migrate my current Vue project to TS, but for now it's just JS. Do you have any recommendation for Vue2-with-TypeScript documentation? Or, even better, a JS-to-TS Vue2 migration guide?


I'll write a blog post about a recommended setup soon. Indeed there are some configuration required for getting all the features working, and they aren't really well-documented now.


To go with this, I would be incredibly happy just to find a complete guide for Webpack + Babel + TS + Vue. The last time I tried I could never quite get anything put together all the way.


I used already configured template for such setup: https://github.com/AbeHaruhiko/vue-webpack-typescript


Why use Babel + TS?


TypeScript opening up plugin APIs is going to lead to a massive number of interesting project. I'm tracking a few of them that are done before 2.3 was out. Very interesting stuff:

* TypeScript CSS Modules plugin [1]. It allows you to type check CSS classes etc.

* TypeScript Vue plugin [2]. Type check .vue files. Competing with the one mentioned in the article

* TypeScript GraphQL plugin [3]. Type check GraphQL queries

I desperately need TypeScript React Hot Module Replacement Plugin. If someone is working on it please let me know!

[1] https://github.com/HerringtonDarkholme/ts-css-plugin

[2] https://github.com/sandersn/vue-ts-plugin

[3] https://github.com/Quramy/ts-graphql-plugin


> I desperately need TypeScript React Hot Module Replacement Plugin

I worked on this for electron-compile but unfortunately React HMR itself (react-proxy) fails with actual classes (i.e. using the `class` keyword not-transpiled) or anything other than Babel's ES5 class keyword transpiler. Once they fix that, apps created via electron-forge or that use electron-compile will get TypeScript HMR automatically.


Since 2.1 ts is becoming a de-facto default choice for any serious JS projects I'd say. In conjunction with VSCode it really shines and makes JS sometimes even enjoyable...

But there is an issue that quirks our team almost daily: the bolted-on typesystem provides a false sense of safety. You can look at an API response, write an interface for the data structure, build functionality ontop of it, and when the API response structure changes in subtle ways over time, everything may break without notice. There is no way to enforce an interface through casting anywhere, not even via some code generation or sth like that.


Codegen your TS interfaces from your server endpoints. You don't need run-time enforcement if you have a compile-time guarantee that the endpoint you're hitting will return a specific type back.

TypeLite (https://www.nuget.org/packages/TypeLite) can get you halfway there with C#. I used that for a while before eventually wanting more and rolling my own solution, which takes a WebAPI endpoint and generates typed fetch methods. It's not anywhere close to polished or reusable, unfortunately.


Use something like https://github.com/lbovet/typson to generate a JSON schema for your interfaces, then use a JSON schema validator before casting the API response to your interface.

I haven't touched TS since ~1.3, but this was all working well back then at least.


Typson hasn't been updated for a while, we use https://github.com/YousefED/typescript-json-schema which works with recent typescript coupled with https://github.com/mafintosh/is-my-json-valid


If you're using F# backend, Gluon generates a typescript RPC. Its saved my team many times. http://www.tachyus.com/gluon/


ServiceStack's solution for this is to generate TypeScript DTOs from Server DTO classes for use with its generic JSON Service Client to enable its end-to-end Typed API:

http://docs.servicestack.net/typescript-add-servicestack-ref...

Disclaimer I work for ServiceStack


I believe there is a way to write type information out to decorators or something like that so you can get access to type information at run time.


does anyone have any detail on this?



I'd love a pro con from someone who's really tried out both TypeScript and Flow. I tried to get either of them started last weekend and couldn't get to a good place. Flow was missing annotations for three.js and typescript didn't seem to support es6isms. I found a compiler for the typescript definitions file for threejs but also couldn't sort out how to actually import that into flow.


We did a very deep dive in comparison between the two before going with TypeScript. The biggest differences are:

1. Number of existing type definitions in DefTyped vs. FlowTyped and packages that provide typings. TypeScript has way more type definitions

2. Tooling, TypeScript has a much better tooling support

3. Project popularity: number of downloads, GitHub issues and pull requests etc. TypeScript is much more popular.

Syntax and personal opinions was not part of our decision making process.


with the checkJs option, now you don't even need to rename your files to .ts, You can just use typescript as a nice typechecker and give you sane .js


Ok, I've used TS while contributing to OSS written with TS and I've used Flow extensively in production settings.

The main takeaway for me is that TS is much much less sound than Flow. That means it checks less invariants which in turn makes you less trust it...

Consider the following code which is valid (!) in TS:

    let promisedString: Promise<string> = new Promise(
      resolve => {
        // Perfectly valid in TypeScript!
        resolve(42)
      }
    )
Another downside of TS is poor type inference. It requires to annotate each top level function while Flow only requires to annotate exported functions.

Even the following simple piece of code will make TS ask you to annotate doAddition function:

    export function addition(a: number, b: number) {
      return doAddition(a, b)
    }

    function doAddition(a, b) {
      return a + b
    }
I'm really glad Flow doesn't force me into it.

Edit: spelling


For your 1st example, it's failing because by explicitly annotating `promisedString` you are widening the type from the inferred `number` to `any`. If you remove the explicit annotation and let TS do its job, the code will fail (as expected) :).

For your second example - it's a divisive issue. I believe that a Hindley-Milner style type resolver (what Flow uses) is more usable, but there is a strong argument against it too [0].

[0] https://github.com/Microsoft/TypeScript/issues/15114


> by explicitly annotating `promisedString` you are widening the type from the inferred `number` to `any`

That's something I don't understand. Isn't that incorrect behaviour? Shouldn't TS try unify RHS and LHS?


TS is trying to unify RHS and LHS. TS follows a somewhat complicated widening process to unify unannotated generics, somewhat leaning towards ease of use over strictness. Adding additional strictness checks like noImplicitAny can help catch these situation. (In this case, it doesn't help, because the resolve argument is inferred `resolve: (value: any) => void` rather than `resolve: any` which would give a clear implicit any error. Inferred any in generic callbacks sound like a good strictness test to add...)

In this case in Typescript it is generally more strict to add a type annotation to the generic than the LHS:

  let promise = new Promise<string>((resolve) => resolve(42)) // This won't work
This is as much because the inference here that matters isn't between LHS and RHS but between generic arguments and function return inference.


I am not convinced that parameter type inference is a reason to use flow. I have seen examples where flow fails to report errors because it can't infer the parameter types. I would rather consistency over inference that sometimes works sometimes fails silently.

For example:

  function fn(a) {
    const {b} = a; 
  
    console.log(b.c);
  }
  fn({});
This compiles without errors - but would fail at runtime. https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVUCuA7AxgFwEs5swp...


Yep, reported to Flow issue tracker.


FWIW your Promise example has to do with whatever implementation of Promise you're using, not Typescript. Bluebird's typings would correctly complain with that example -- both because your second Promise is implicit-any, and the resolve is wrong.


EDIT 2: This still surprises me...

   let promisedString: Promise<string> = new Promise<string>(
      resolve => {
        // Perfectly valid in TypeScript!
        resolve(undefined)
      }
    )
EDIT: no, I was wrong — Bluebird typings won't allow this behaviour but they force me to annotate both the binding and the Promise constructor call:

    let promisedString: Promise<string> = new Promise<string>(
      resolve => {
        resolve(42) // type error here, ok
      }
    )
That's surprising TS ships with such unsafe typings for ES2015 Promise API...

Hm... no.

First, note that this is with noImplicitAny activated. You can check this in TS playground.

Then if we inspect what typings TS have for ES2015 Promises[1] and for Bluebird[2], you can clearly see that those are identical in this case..

[1]: https://github.com/Microsoft/TypeScript/blob/master/lib/lib....

[2]: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast...


Er, I'm looking at it right now? I don't know what to tell you.

   error TS2322: Type 'Bluebird<{}>' is not assignable to type 'Bluebird<string>'.
And if I add the type parameter to the constructor...

   error TS2345: Argument of type '42' is not assignable to parameter of type 'string | Thenable<string>'
Re: your edit, you actually don't need that first typing. Typescript will infer the type of the promisedString.


> your edit, you actually don't need that first typing. Typescript will infer the type of the promisedString

Ok, but still this is confusing, it can't infer the type of RHS given the annotated LHS? Intuitively there's nothing wrong with it and Flow does that well...


Note this is similar to c# (and thinking about it, every OO language I can think of):

var cat = new Animal<Cat>(...); // yup! Animal<Cat> cat = new Animal(...); // Nope

I wonder if internally ts is treating these generic-accepting classes in the same way, where the generic is required?


Uhhh nope. In TypeScript 2.2.2 your first example is definitely the error you'd expect.


Try it in the playground.


Interestingly enough #1 seems more like another case of #2, because:

    let promisedString = new Promise<string>(
      resolve => {
        // Fails as expected in TypeScript!
        resolve(42)
      }
    )


Not sure — TS doesn't report any errors in the original code so I assume it thinks code is fine but it is not. That's totally different than #2.


Looks like the Promise example will be fixed in TypeScript 2.3.1

https://github.com/Microsoft/TypeScript/issues/14770


> The main takeaway for me is that TS is much much less sound than Flow

And in personal anecdote-space I've experience the exact opposite :)


Well, I've provided examples where TS demonstrates unsound behaviour while Flow does well. What's your examples from personal anecdote-space?


I've tested your example and sure: That seems like a bug in the declaration of the Promise-class.

What I like about TypeScript and which I think is "sound" compared to Flow is the whole experience and how it is backed by good tooling.

With TypeScript I can open almost "any" editor and expect it to understand and respect the typings of all my TypeScript code. It will correctly autocomplete, and tell me when I'm using undefined members.

Basically with TypeScript every part of the stack seems to work for me, the developer, to ensure I make the right decisions and get the assistance I need, at all time. That makes it feel like a very safe and sound language to write code in.

With flow? Well fuck that. From what I can tell, you get almost nothing.

You can run your compiler and see if it validates, but I've seen almost no editor-support worth mentioning, meaning that while the type-inference in the compiler may occasionally be better (but for how long? TS has a ton of momentum), the overall experience feels much less sound and much more fragile. Much more unsafe.

The type-declarations definitely feel as important as the way they are declared: they're mere comments. They're not real.


As far as type systems/language features:

TypeScript:

- Structurally typed

- Enum types

- Mapped types

- Abstract classes

- Scoped class members (public, private, protected)

- Namespaces

Flow:

- Nominally typed

- Covariance/contravariance annotations

- Supertype annotations (via $Supertype type)

- Subtype annotations (via $Subtype type)

- Arity annotations (via $Pred type)

- Subtraction types (via $Diff type)

- Opt-in 2-way type resolver (via * type)

- Refer to nested type (via $PropertyType type)

Otherwise, the two are remarkably similar.

I've been using TS for a few years, and Flow for a few months. Please correct me if any of the above are wrong.


In Flow only classes are nominally typed. Objects and interfaces are typed structurally.


Thank you for the comparison. This basically matches my experience as well. Hoping your post gets up to the top.


Flow is basically a linter, which I really don't like. If you run flow on an existing JS project it will find a few hundred not-really-bugs. That and the incredibly poor tooling (Flow runs as a separate server process) were enough to make me ditch it. On the other hand, if you use Typescript with the allowJs setting it's exactly ES6 plus optional types.


What es6 features were you looking for that TS didn't support? In general, it supports most stage 3 and higher ES proposals. (Note that TS doesn't polyfill methods; it only adds support for syntactic elements)


I suspect you didn't set target to ES6 in the `tsconfig.json` file which would limit some of the features. If you don't specify, I think the default is ES5. See this example:

https://github.com/styfle/react-server-example-tsx/blob/mast...


I haven't used Flow much, but having used TypeScript at work for only a few weeks we've already found several instances where the type system isn't flexible/complete enough to describe several perfectly valid JavaScript idioms. Workarounds often mean lots of `any` types or tons of boilerplate/repeated code. Not fun. On the whole, though, compared to un-typed JavaScript, still totally worth it. I'd just be interested to see how Flow handles some of these situations.


Do you have an example of one of these idioms that typescript can't handle?


Could you please post those situations? Someone familiar with Flow might be able to answer you.


I'd love a pro con from someone who's really tried out both TypeScript and ES6 Javascript. What exactly is the use case that TypeScript allows one to write JS for that one can't just write JS for?


I've been using both for a few years (TS at my old job, es6 at my new job but we're moving to TS so now I'm using both depending on what I'm working on).

The use case I like most about typescript is it makes refactoring and making changes really painless. For example, in an angular app, you may have a service that several components rely on. When changing a method signature in the service, you'll get compile-time info about any other usages of that service, and you feel a lot more confident about making changes without something dumb slipping through the cracks and causing bugs in production.

This confidence generally lends itself to less fear of change and more willingness to refactor, which leads to a better/cleaner codebase.

Aside from that, I love the JSDoc comments showing up as you type, especially if you're working on a team in which you may not know 100% what everyone has worked on.

Other features I use every day and love:

-automatic/generated import statements

-type definitions for libraries (most have solid documentation)

-control-flow logic checking (you'll find more bugs than you think with this and it encourages more defensive programming)

-transpiling down to support older browsers (babel does this too but it's nice to have it built in)

Edit: I forgot to go into the "cons" list here.

-there's some finagling you'll have to do with some of the more poorly-written npm packages that strap themselves onto globals

-there's a slight learning curve

-you'll require a build step (with es6 if you're targeting es6-only browsers you can deploy just static files, but most people use webpack/babel anyway for older browser support and other things webpack gives you like bundling/minification/etc)


> you'll require a build step

I'd like to note that this is done automatically in Visual Studio 2015 and on. You just save your .ts file and VS will create the .js file.


While IDE transforms can be handy when getting started with small projects, you cannot use them for automated builds (projects with multiple contributors, continuous integration). Any serious project using TS does indeed require a build step.


As much as I will fairly praise Visual Studio, thanks for pointing out this automatic generation feature

I'm not by nature keen on automatic behaviour, or files appearing wherever, and though I visited this story simply to check in on the state of a language I know less than I want about, I'm certain that I would want a proper build step even for tinkering, once I start in earnest. I've long been enthusiastic about TypeScript especially, but from a distance, unable to allocate time to take it seriously enough.

I think the state of js and environment is now at a point that, in my view at least, I should not begin the smallest project without a deep dive into the state of the language. I see things moving so fast, that - at least in my workplace where we've had teams stick together for years commonly (partnership!) - it would suck to find oneself misdirected by a aggressive assumption, or find oneself in a unloved cul - de - sac of dependencies.

Tl;dr js is IMO at a place where the pay off for deeply studying the state of the language, is substantial while risk of not deeply groking js are rising fast.

Personally, I think I shall better resort to getting a new shelf of good books, for my needs, but I do believe the risk reward is looking hairy for any casual users. (or hurried business management, in particular)

I'm a little surprised, given my understanding the impression I had of ts is the very broad aim is to reduce your error in code, (type safety only part of that) that VS will encourage casual / random deployments like this. I can't decide if it's a occasional convenience quite suited to weekend js ciders like me, or a omitted formality that I feel encourages poor or slack habits.

Funny thing is, I never once thought of firing up VS to write JavaScript before now. I have no need, but I'm just displaying my age when I note that visually my mind thinks of early Netscape view source spelunking and text editors, not a actual IDE and build system.

What keeps me, well into a fourth decade of programming, from using JavaScript I think is only the fact that I totally phase out at the state of the tool chain for js. My mind blanks. But there's so much to like, using js, that i hope it's not abandoned by time I get to really learning it. (forgive my humour, but my first real computing experience was on a Symbolics 3650, then spanking new. Last week wanting to show a friend what one looked like, I found kids veritably boarding them! (sorry for the kids part, but it's nuts I found such phrases creeping up on me, I'm lucky in looking less than my years, but when did I start saying things like "the kids are doing x"? I want to know what causes this, and if there's a cure!)

Edit: Typos, minor clarity


The killer feature of Typescript is being able to model data. Most serious bugs I see in JS applications are because somebody serializes something from JSON, passes it around, and somebody somewhere makes incorrect assumptions about the data. Being able to type my models, Redux state, config objects, etc is a huge boost to developer productivity and maintainability.


^ all of which is of course available in Flow as well (in case OP got the wrong idea.)


Isn't that rather more fundamentally a documentation failure? Or communication failure, if data producers are expected to signal protocols where you work. Else a formality oversight for the data consumer developer to not seek documents and check your specs?

True, it _results in a bug. But when bug count gets high, and I see a noticeable percent originating from slacking habits, I start prowling to find who's been pulling too much overtime or something family is tiring them out. Nine out of ten times, it's someone who needs only firm advice to look after themselves better. Where I work age skews much higher than SV norms, so young children and other delights (not /s at all) have notable impact on code quality.


Not really. There's intrinsic value in being able to type a variable name and see all it's properties without having to look up documentation -- especially if it's code you're not familiar with. One less thing you have to balance in your head.


Very good point.

I quite commonly get a wood<>trees occlusion, when I'm thinking through my own habits, to visualize the world. I've just made documentation such a important part of my working life that I am constantly thinking through that structure. It began with a prospective business partner trying to blackmail my company in part by withholding key metadata for a important deal. The deal that founded my company, in fact. I know I was scarred badly by that. And this was a important friends, ten years my senior, without whose advice I would have..i don't know what other path... So I made self documenting a whole schedule in the partnership. Forget living off a LP interest in retirement, if you pull a stunt like the one that nearly bankrupted us before we started. (unlimited liability! We are since a limited partnership, but the fact we were a general partnership actually saved our houses on that first deal. The customer CEO actually noticed our names as one does put them on the letter head. Suddenly calls were made, subsidiary directors were gotten at home to listen up... Our customer CEO sussed how much we had on the line. The world changed in a instant. Not a small customer the kind you think might cate, either, DAX30! Edit to say I doubt any but a German boss would spot a partnership firm by letter head. &co KG is a very common incorporation form, UK L.P. also permits a limited entity as gp. UK lp can be domiciled wherever you like, too. If anyone will be helped by any experience i might offer, just drop me a line, I believe some of our long observations could have genuine assistive value for starting ventures. Specifically for any non UK nationals still wanting a post Brexit presence at minimum exposure. Banking for these partnerships can be tricky, or you may simply be blanked by confused staff, but I've has good experience i can relate if you need to bank in the UK for a project. N.b. UK L.P.s are not taxed at the corporate level, only your personal income can be taxed. The potential for compounding gains when yours small and growing, is nothing to be sniffed at)


I have only superficial experience, but the biggest benefit of typescript over flow is the tooling. It is easy to setup, with transpiling, JSX, linting, webpack loader all bundled together, while with flow you have setup a lot of different components yourself, which may not interact well with each other.


Heard a talk about that a while ago. Here are the slides maybe you can get something from them. https://djcordhose.github.io/flow-vs-typescript/2016_hhjs.ht...


Highlights / tl;dr:

- ability to check .js files

- default type parameters (eg; `class Component<Props, State = object> {}`)

- generators/iterators (including async-generators, a stage 3 proposal).

- `--strict` flag to easily give you --strictNullChecks, --noImplicitAny, --noImplicitThis, and --alwaysStrict

- language server plugins are official (the Angular and Vue ones were promoted in particular)


I wish TS would consider the annotation-in-comments form from flow: https://flow.org/blog/2015/02/20/Flow-Comments/

For switching a large existing JS codebase, it's easy to add flow comments without changing the final minified builds, allowing you to reap the full benefits of the type check.


TypeScript allows for JSDoc Comments for types in .js files with `--allowJs`. you do not need to change your code for that.

See https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-i...


Thank you! I've been trying to figure out how to get JSDoc-ed code to get appropriately typed in Visual Studio Code with Typescript files as well.


Now that typescript can compile generators down to ES5 and ES3, you could reasonably replace Babel by tsc entirely, right? I mean, with its --allowJs flag it's really just a javascript transpiler. Async/await, generators, JSX, array/object spread, destructuring.. it's all in there.

Did anyone try this? We're doing a hybrid babel/ts app and it wouldn't hurt ditching one of the two tools.


I've replaced Babel all together for an app using webpack - I use the unfortunately named https://github.com/s-panferov/awesome-typescript-loader

If there's something you really need in Babel, you can always transpile to ES6, then put it through Babel.


Right I've never needed to use Babel, webpack + TS is now my choice combo. Being able to use latest ES6/7 features is one of the main reasons why I now use TypeScript for all my JS projects, even small ones that contain minimal Type annotations.


That's exactly what I've been doing since 2.1 came out. We get to use async/await, object spread etc but still get it compiled to ES5. Haven't had any trouble getting it working with React either.

It did need some tweaking to the tsconfig.json file, but that's a one time setup.


You still need to provide some polyfills


That might be a great idea for a plugin: add warnings/errors and automatic code fixes to import core-js (or similar) polyfills based on code usage.


My personal Gem in this release: Generic parameter defaults. [0] This makes altering a generic interface or a generic type alias in a non-breaking way much easier which is very powerfull in a large code base.

[0]: https://github.com/Microsoft/TypeScript/wiki/What's-new-in-T...


This is fantastic!

Allowing type checking on js files with comments will allow me to start improving our exciting hard to maintain large code base. I attempted to do this with flow as well before, and it did the job well enough (although at the beginning I ran into a number of issues), but I have a preference for TypeScript, and the next time I work on that project I will likely be doing heavy usage of this.


With VSCode 1.12 (aka the current insiders build) you can also enable JavaScript type checking without creating a jsconfig.json or even changing your source code by setting "javascript.implicitProjectConfig.checkJs":true in your workspace or user settings. This setting applies to any JavaScript file that is not part of a jsconfig or tsconfig project. Besides catching errors, checkJs also enables a number of quick fixes in JavaScript files.

Please let us know if you see any errors while trying out new TypeScript 2.3 features in VSCode or have any thoughts on how our JS/TS support could be improved: https://github.com/Microsoft/vscode/issues/new


I agree. Additionally, it looks like the comments feature is compatible with the JSDoc syntax. I'm not too sure about the return syntax though. This means I can start type checking some of the large and older JavaScript projects, all documented with JSDoc, of some of my clients. I'm eager to test this out.

In my experience, in some organisations, it's hard to introduce TypeScript instead of JavaScript, because of reasons. For example, one of my clients made a bet on CoffeeScript back in the days, and that didn't work out, so now they are hesitant to adopt anything. Being able to introduce at least the type checking feature will start to drive change to this hesitation.


The language service API is huge! One of the main reasons I even bothered to learn React was because TypeScript supported type checking JSX.

Back when I picked up TS, I was using Handlebars for templating. The templates were the only part of the code that didn't type check which was really annoying when doing something like "Refactor all references". I tried to write my own templating[0] and realized I was basically reinventing JSX, so I wrote a react boilerplate[1].

The language service is going to make Vue, Angular, Svelt, and any other template syntax way more attractive.

[0]: https://github.com/styfle/typed-tmpl

[1]: https://github.com/styfle/react-server-example-tsx


The GraphQL plugin[1] looks great. I was eagerly waiting for Flow's tooling to catch up because of their GraphQL support, but I guess TypeScript is running laps :)

[1] https://github.com/Quramy/ts-graphql-plugin


I hope TS adds native Swift-style optional values and chaining, where it fails at compile time if you try to access an optional without unwrapping it first. Conversely non-optional values cannot be null!

There are projects that add optional functionality (https://www.npmjs.com/package/ts-optional), but I don't see how it prevents you from setting regular values to null.


I use type sugar in my projects. This helps communicate what might be null/undefined. I haven't been satisfied with something like ts-optional since it wraps the object in a function (or class, or prototype?), making it harder to serialize to JSON.

    /** Represents optional values, just as F# does. */
    export type Option<T> = T | null | undefined;

    /** Option operators. */
    export namespace Option {
        /** Constructs a Some(value) option. */
        export function some<T>(value: T): Option<T> {
            return value;
        }

        /** Returns true if the value is Some value and false otherwise. */
        export function isSome<T>(value: Option<T>): value is T {
            return value !== undefined && value !== null;
        }

        /** Constructs a None option. */
        export function none<T>(): Option<T> {
            return null;
        }

        /** Returns true if the value is null or undefined and false otherwise. */
        export function isNone<T>(value: Option<T>): value is null | undefined {
            return value === undefined || value === null;
        }

        /** Recovers an Option<T> from JSON object representation. */
        export function fromJSON<T>(json: any): Option<T> {
            return isSome(json) ? <T>(json[0]) : null;
        }

        /** Converts to a JSON representation. */
        export function toJSON<T>(value: Option<T>): any {
            return isSome(value) ? [value] : null;
        }

        /** Unpacks with a default value. */
        export function withDefault<T>(value: Option<T>, defaultValue: T): T {
            return isSome(value) ? value : defaultValue;
        }
    }
EDIT: Forgot to mention, I got this from Gluon. https://github.com/Tachyus/gluon/blob/master/src/Gluon.Clien...


Have you looked at TypeScript's non-null types[0]? It gives you compile-time checks for values that might be null. I personally love it and use it for all my projects.

[0]: https://blog.mariusschulz.com/2016/09/27/typescript-2-0-non-...


Isn't this just the strictNullChecks flag?


What do you mean by "Swift-style"? TypeScript allows you to declare optional values on an object:

interface Test{

number? myOptionalNumber;

}

Is that what you mean?


It is. I guess then you have to use the --strictNullChecks compiler flag to get the rest of the benefits


Not sure if this "type checking with comments" is a good thing or not. On one hand it might convert some hesitant users, on the other hand it will cause some code bases to stay like half assed js-with-comment-annotations forever instead of being converted to proper typescript once and for all.

It will also require extreme discipline, like a CI build machine checking each commit, because the comments allow clueless people to edit the code like plain JS and not get any compilation errors, later when the next person comes and edits it with a typescript compiler they will get a broken build. If everybody works under the same circumstances, i.e always typescript, this is less likely to happen


I wonder if the plugin system will evolve into an AST-transform ecosystem like Babel's.


I hope not. Didn't we already learn this lesson from macros? Having code that appears to do one thing but actually does something very different is a maintenance nightmare. Once the people who decided to add that AST transform plugin are gone and new people take over that don't know about it, the trouble really starts.

Again, we've seen this in languages with macros. At least with macros it's part of main codebase; you usually have to include them in some way. With these AST transform systems the secret is tucked away in a build script somewhere.


I've had poor experiences with PostCSS w/ regards to AST transforms. The different plugins tend to not interact with each other at all because they're just transforms. Feels worse than something that works together all around like scss.


Much of this, IMO, is due to a lack of a type system.

The maintenance nightmare comes from when behavior changes and you have no way of knowing about it - a type system staves off some of this.


There's already a way to consume TypeScript through its API and inject a custom transform today, so a lot of the machinery is already in place.


I hope so – so far it looks a lot less powerful.

One aspect that's disappointing to me is that the AST they use seems fairly idiosyncratic; Babel's is quite close to the ESTree spec, and even easier to work with.

Relatedly, it also doesn't look possible to swap out the parser, which Babel makes easy. I'd love to use the TS typechecker for a compile-to-js lang I'm working on ([0]), but would need to use my own parser.

[0] http://lightscript.org


Hi Alex (I have an email from you that I have to respond to)! TS guy here. We've had discussions around this and the reason we use our own AST format is for compilation speed and editing scenarios, both of which our team really focuses on.

I'll also note that incredible folks like James Henry have already written tools to convert TypeScript ASTs to the ESTree format[1]. I've heard it's been working well for using ESLint on TypeScript code.

[1]: https://github.com/eslint/typescript-eslint-parser


Hey Dan! Yeah, prettier has also been working hard[0] towards TS support, frequently referencing typescript-eslint-parser (I haven't been involved).

Personally I want to go the other way – ESTree to TS – so while the prior art is helpful, very little of the code could be reused.

If TypeScript (or a fork thereof) exposed an option to use your own parser, an ESTree -> "TSTree" library could be used to map the output of any babel plugin to TypeScript. I'm sure you've discussed/considered this; presumably speed is a top concern.

[0] https://github.com/prettier/prettier/issues/13 and https://github.com/prettier/prettier/issues/1306


for all the problems I have with Microsoft and some of their other products, I really have to say that the typescript and vscode teams are doing a phenomenal job. Every release is a vast improvement over an already great set of tools. don't think I've been as excited to see new release announcements since the early days of Firefox.


Was @ts-check just added in this version? I assume so, but if not -- is it possible to use TypeScript and just @ts-check and get basically the full type-checking power (assuming the items to be checked follow the standard lib)?


you could. jsut add `@ts-check` in your .js file, open it in VSCode, or pass it to the `tsc --allowjs a.js` on the commandline.


>Previously, TypeScript didn’t support compiling generators or working with iterators.

I had no idea. That seems like a big deal, no?


It didn't support transpiling generators to es5. Compiling to es6 would work and you could add babel to transpile down to es5 so in practice this wasn't much of a problem.

Async iterators are very exciting and builds should be faster without babel in the pipeline.


I just upgraded our version to TS 2.3, removed Babel (which we were using for generator support), and it cut our build time in half.


Anders and team are like programmer whisperers. Every design decision has been a productivity boon.


Well they listen to their users and community. Their PMs do a fantastic job at outreach, listening and prototyping things that would make life easier for developers.


If only the Flow team was half as active as TS. Is there even any reason to use Flow long term or are they eventually going to tell their users to either switch to TS or that ML thing of theirs?


The checkJS option is awesome. I believe a ton of opensource JS projects on the web can benefit from this. Unlike flow which is written in a different language and has little tooling, typescript can now just act as a type checker, with vscode offer great intellisense and generally play very well with existing build tools.

This is just fucking awesome. I see Types as a way of documenting your code for the other team members who will use your API.


added type checking for JS files // @ts-check in similar fashion to //@flow Trying to eat up market share from Flow


It's a good thing, competition is a fuel of innovation :)


Yes, especially between two large corporations. If Flow was created entirely by open-source enthusiasts I would be worried for the project. Since it's FB vs MS, well let them bring the best of their minds.


TypeScript, a higher level version of something that is super high level in the first place. So it's converting from one scripting language to another, not straight down to byte code. So you are developing a sitcom for the Northern American market, but decide to write it in Mexican Spanish, to be translated to American English. Great! It has the same issues as ORMs. Javascript isn't that hard. As for ORMs - How many database changes are you planing on doing? ORMs seam nice for simple stuff, but still ended up slowing stuff down just on the simple stuff (See translating to Mexican Spanish to American English). Start doing complex stuff like joins and join with extra information, then it's just that much overhead.

If you can't do JavaScript, find someone that can. Can't do query in which ever database, find someone skilled in said database. Can't do CSS... Can't do HTML, GTFO of the business.


TypeScript isn't higher level than JavaScript. It is JavaScript, just with a lightweight type system. It doesn't make things "easier" than JS, it makes the process of building large JS apps less error-prone.


TypeScript isn't a higher level of JavaScript, it's ES6 with added features and types.

Main purpose is to make JavaScript code easier to maintain, especially across teams.

IMO the only way to go "higher level" is to use something like jQuery.


I'm curious, what frameworks are people using TypeScript with? Is it mostly Angular or are people using it with others also?


I've been using Typescript for a while and have used a lot of frameworks for it, and some lack of frameworks (one of my earliest Typescript projects was a large conversion of an enterprise JS code base consisting of a mixture of JQuery 1.x, Backbone, and Knockout code). These days I've got one big project in Aurelia (which I'm not entirely thrilled with sometimes) and another in Cycle.js (which is quite cool and I'm using TSX there even).


I'm actually using it for the app logic/container in a riot.js app. Libraries like React/Riot/Vue are happy just being views in your Model-View-Whatever.

Angular is another story.


React, AngularJS v1, basically everything that more than 100 lines of js code.


We use both Backbone.js and React.


Would the plugin system allow for things like conditional compilation or closure-like optimizations?


No, to my knowledge the plugin system won't allow extending the compiler's knowledge of new symbols inside a source file


I've been using Dart for a few months. What advantages does TypeScript have?


I know MS has really changed lately and even I have taken to using their Visual Studio Code editor instead of vim. But it's kinda funny that the first link I click in this blog post is 404. :) Classic MS.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: