366 points · by DanRosenwasser · 9y ago · 116 comments
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
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?
* 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
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.
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.
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.
I haven't touched TS since ~1.3, but this was all working well back then at least.
http://docs.servicestack.net/typescript-add-servicestack-ref...
Disclaimer I work for ServiceStack
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.
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 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].
That's something I don't understand. Isn't that incorrect behaviour? Shouldn't TS try unify RHS and LHS?
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... 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...
let promisedString = new Promise<string>(
resolve => {
// Fails as expected in TypeScript!
resolve(42)
}
)And in personal anecdote-space I've experience the exact opposite :)
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.
https://github.com/styfle/react-server-example-tsx/blob/mast...
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)
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.
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.
- 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)
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.
See https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-i...
Did anyone try this? We're doing a hybrid babel/ts app and it wouldn't hurt ditching one of the two tools.
If there's something you really need in Babel, you can always transpile to ES6, then put it through Babel.
It did need some tweaking to the tsconfig.json file, but that's a one time setup.
[0]: https://github.com/Microsoft/TypeScript/wiki/What's-new-in-T...
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.
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
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.
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.
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.
/** 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...[0]: https://blog.mariusschulz.com/2016/09/27/typescript-2-0-non-...
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
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.
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.
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.
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.
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
I had no idea. That seems like a big deal, no?
Async iterators are very exciting and builds should be faster without babel in the pipeline.
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.
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.
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.
Angular is another story.