
Svelte and TypeScript - kevinak
https://svelte.dev/blog/svelte-and-typescript
======
Vinnl
It's really telling that, for every big project that does not support
TypeScript, the number 1 feature request is TypeScript support. (And
consequently, that there are fewer and fewer such projects.)

~~~
tester756
I think that's just proof that "the next future" of web development is going
to be owned by languages like C# (that __already__ allow you to write decent
client side web apps) and other already popular not dynamic languages

After C# of course yet another DSLs.

~~~
k__
I hope not.

C# is too bloated for my taste and I have to admit, TS is too close to C# for
my taste.

~~~
Vinnl
If it's like C# in that it's bloated, I can see why you might say that, but
I'm quite sure that my TS code looks nothing like C# code. (Because it's
almost exactly like my JS code, but with annotations and fewer redundant
checks.)

~~~
k__
To me, C# like type annotations, especially generics, look bloated.

ReasonML files don't look like that and are even sound.

------
wry_discontent
I feel like the odd man out in discussions like these. I don't like Typescript
and I regret pushing to integrate it into a project at work.

I've found it vastly increases incidental complexity and affords little to no
benefit to me. The IDE completions are nice, but ultimately not worth the
price, in my humble and honest opinion.

~~~
keb_
I also disliked my time with TypeScript, but perhaps its value hasn't made
itself entirely apparent to me. Most of my programming experience has also
been with dynamically typed languages. I think if you had already spent enough
time with a language like JavaScript or Lua and familiarized yourself with its
quirks/footguns, you learn how to avoid the common pitfalls of not having a
strict type system.

Although I've found that TypeScript is a great way to attract devs who hate
JavaScript to try working on front-end.

~~~
cageface
When working with devs that have grown up on dynamically typed languages I
often find that they have not really thought carefully about the structure of
their data and there are essentially many ad hoc data types strewn throughout
the code. Thinking in types from the beginning leads to much better structured
code and stronger abstractions IMO.

~~~
wry_discontent
I see the same thing, but in people who primarily work in statically typed
languages. I don't think there's much of a pattern in wrt types, but people
who don't think about data.

~~~
cageface
Specifying all those complex ad hoc data types in a statically typed language
is so tedious I think it pushes you to start looking for unifying
abstractions.

------
vosper
Lack of Typescript support was the main reason I didn't switch to Svelte for
my personal projects. Other than that it was a joy to use, and a breath of
fresh air in it's approach.

I'd recommend any front-end dev to give Svelte a try, even just spending an
hour or two messing around, to experience a way of developing web apps that's
likely a bit different to what you're used to, but feels familiar enough that
it doesn't require a big mental leap.

------
swyx
Here are some tutorials from community members who knew this was coming:

\- 3 min youtube demo:
[https://www.youtube.com/watch?v=djRkyyBoIKs&feature=youtu.be](https://www.youtube.com/watch?v=djRkyyBoIKs&feature=youtu.be)

\- 3 min eggheadio lesson: [https://egghead.io/lessons/svelte-create-a-new-
svelte-projec...](https://egghead.io/lessons/svelte-create-a-new-svelte-
project-with-typescript-support)

\- TS + Sapper:
[https://mrsauravsahu.github.io/blog/38/](https://mrsauravsahu.github.io/blog/38/)

------
nickreese
Having talked to a ton of friends about Svelte, Typescript support has always
been the biggest push-back for adoption.

Stoked for Svelte to support it.

We've been using Svelte in production and I can't speak highly enough about
the developer experience. Absolute game changer for our ssite that use it.

~~~
The_rationalist
What would it bring in ergonomics and expressivity versus Vue ?

~~~
kjksf
Those things really need to be experienced to be understood, so just try
Svelte in a toy project. Or go through the interactive tutorial
[https://svelte.dev/tutorial/basics](https://svelte.dev/tutorial/basics)

I used both React and Vue and am now only using Svelte.

You type less. Significantly less.

The thing you type is simpler. I tend to get lost in Vue's object structure.

What you type is closer to HTML/CSS/JavaScript than what you type in
React/Vue. It's therefore easier to understand what gets generated.

The seamless reactivity is awesome.

Scoped CSS support is built-in so you don't need css-in-js hacks.

Built-in support for data (stores) is excellent.

The final bundle is smaller and faster.

There's more but the above are the major points.

The only downside is smaller ecosystem. But I don't care because I'm in the
camp of minimizing my dependencies.

~~~
preommr
> Scoped CSS support is built-in so you don't need css-in-js hacks.

vue/react also have scoped css, but built into the building process using
loaders rather than being a feature of the frameworks.

~~~
buzzerbetrayed
Less time setting up build processes is another win you git with Svelte, in my
experience.

------
orange8
> I get almost as much benefit from the rigorous null checking in TS as I do
> from the typing. I would use it for that alone. [1]

This.

I suspect there is a certain way those who rave about TS like yourself write
and structure their code (all code, regardless of language) in a way that
naturally lends itself to strict typing. The "rigorous null checking" comment
struck me as odd, as someone who has written JS for almost 20 years, I've just
never had to think about, or use null values. I probably just use the good
parts of the language and avoid the bad [2]

[1]
[https://news.ycombinator.com/item?id=23913294](https://news.ycombinator.com/item?id=23913294)

[2] [https://www.oreilly.com/library/view/javascript-the-
good/978...](https://www.oreilly.com/library/view/javascript-the-
good/9780596517748/)

~~~
spion
You can't avoid null and undefined in your code unless you avoid almost every
language feature. Two particularly common ones:

* Accessing a missing property or method results with undefined. Hope you remember the exact method names and field names of all objects in your codebase!

* Using "str".match(regex) results with null if there are no matches.

~~~
orange8
> You can't avoid null and undefined

We are speaking about just null, not "null and undefined". Believe it or not,
I simply do not use null in JS. Study the concept of "truthy and falsy" in JS.

> Accessing a missing property or method results with undefined. Hope you
> remember the exact method names and field names of all objects in your
> codebase!

I don't. I do however structure my code predictably, using consistent naming
conventions and patterns. I hope you do realize JS existed for over 20 years
before TS, and complex apps like gmaps and google docx were built entirely in
JS.

> Using "str".match(regex) results with null if there are no matches.

const match = /bar/.exec("str");

if( match ){

    
    
      // am only interested in what happens if foo returns a *truthy* result.
     
      // The exact type of a falsy result is irrelevant, it either matches (truthy) or it doesn't (falsey)
    
    }

~~~
schwartzworld
> We are speaking about just null, not "null and undefined". Believe it or
> not, I simply do not use null in JS. Study the concept of "truthy and falsy"
> in JS.

I'm anti-TS, but there is a meaningful difference between null and undefined.
Most of the time it's enough to check for falsy values, but there are times
when you will want a distinction between a missing value and a value of null.

[https://i.stack.imgur.com/T9M2J.png](https://i.stack.imgur.com/T9M2J.png)

~~~
orange8
Do you have a concrete example of such a time?

~~~
schwartzworld
Undefined represents the absence of information altogether. In JavaScript any
key can be called on any object and if it doesn't exist it will return
undefined. If you put a typo in the key name, you get undefined. If you've
never set it, you get undefined.

Null, on the other hand, is not a lack of information. It's an absolute value
just as much so as any number or string or array.

They're both falsey values, but so is the number zero. An item with a price of
zero dollars is not the same as an item with an undefined price, nor is it the
same as an item that explicitly has no price, i.e. null. You may not choose to
model your data that way, but the terms are still meaningful, and your UI
might have to change to reflect the different falsey values.

Most common case I could think of, would be in making a request from a server,
using something like Apollo. `const [ data ] = useQuery(SomeQuery)` The data
that comes from the server is undefined until you make the request, but null
could be a valid response.

------
nojvek
TS really shines when you have to work with other people’s code. This week I
probably touched about 2000+ files and changes various apis. TS was really
great in giving that confidence that what I am calling actually existed.

I had ~2000 errors and slowly worked to 0. tsc —watch is so good for iterative
development.

And LSP (Language Server Protocol) really is a boon for the industry. So many
tools can work together. Thank you VSCode for paving the way to an open
protocol.

------
seanwilson
Are the HTML templates type checked as well?

I'm playing with Vue version 3 with TypeScript using JSX instead of the usual
HTML templates and pretty happy that it's all type checked. I have a similar
project without JSX and the vast majority of the bugs are related to the logic
in the HTML templates not being type checked.

~~~
smt88
Try using Vue in WebStorm with their Vue plugin enabled, or use TSX with any
IDE. Your "HTML" will be type-checked.

~~~
joshstrange
Hmm, I'm going to have to take another look at this then because I get auto-
complete of variable properties in my html (IDEA + Vue plugin) but I don't get
warnings about a variable possibly being null or undefined. But that may be
outside the realm of possibility to check easily.

~~~
smt88
> _But that may be outside the realm of possibility to check easily._

It depends. If you type-check your runtime input (e.g. form fields) then it
works well.

------
dboreham
Switching from JS to Typescript was like moving from machine code to C. Note:
machine code (hex) not assembler.

~~~
DaiPlusPlus
JavaScript is getting more “typed” anyway - what with Promises and other
objects/interfaces in the DOM being conceptually statically typed - where
JavaScript’s type-juggling simply can’t help you - so writing JavaScript today
against modern browser/NodeJS APIs feels like writing VBScript against ActiveX
instead of writing in VBA/VB6: you can do essentially the same things, but you
have no idea if your program will actually work or not.

It would not surprise me if the ECMAScript folks just throw in the towel and
adopt TypeScript into ECMAScript as its official type-annotation feature -
like how Python is doing - except without the duplication of effort.

------
swyx
this has been eagerly anticipated for so long and is probably the #1 stated
reason why people haven't tried out Svelte yet. so glad this is out!

~~~
outime
It definitely was my #1 reason and I'm happy to see this announcement. I'll
check Svelte out soon as it already looked quite promising to me.

------
jedimastert
I am a (very) hobbyist web dev, almost always working with vanilla HTML+JS. I
seeing a while lot of people here who are saying that Typescript is an
absolute must.

As someone who has no clue, and with all do respect, why would TypeScript be
worth moving from just hitting save to introducing a build system and
dependencies?

~~~
runarberg
I have been using TypeScript in JS[1] mostly seamlessly. Types are annotated
using doc comments above the thing your annotating.

It is a bit hard to define complex types. E.g. I couldn’t for the life of me
annotate the return value of the pipe function:

    
    
        function pipe(init, ...ops) {
          return ops.reduce((acc, op) => op(acc), init)
        }
    

For these instances they suggest writing a declaration file[2]. However I have
found the documentation isn’t really clear on this usecase (in fact I find the
documentation of TypeScript somewhat lacking in general).

But overall getting these typehints into my editor environment has been worth
it. And I haven’t had to sacrifice the save → run workflow.

1: [https://www.typescriptlang.org/docs/handbook/type-
checking-j...](https://www.typescriptlang.org/docs/handbook/type-checking-
javascript-files.html)

2: [https://www.typescriptlang.org/docs/handbook/declaration-
fil...](https://www.typescriptlang.org/docs/handbook/declaration-
files/introduction.html)

EDIT: An example annotated JS file for typescript:
[https://github.com/runarberg/strawberry-
router/blob/master/s...](https://github.com/runarberg/strawberry-
router/blob/master/src/elements/router-view.js)

`npm run check` just runs typescript’s type checker, there is no compile step.

~~~
xsmasher
If I understand your pipe function correctly - it takes an init value and a
series of functions that map a type T to the same type T - then this should do
it.

    
    
      function pipe<T>(init: T, ...ops: ((x: T) => T)[]): T{
        let r:T = ops.reduce((acc:T, op) => op(acc), init);
        return r;
      }
    

I had 5 years experience fixing type errors in C++; typescript seems like a
dream in comparison.

Edit: I just realized your operations probably DON'T return the same type that
they are passed; they probably work in a chain like (t:T) => U, then (u:U) =>
V, etc. Nevermind!

~~~
runarberg
Yup, the annotation should be something like:

    
    
        type Ops<T, R, N> = [
          (x: T) => N[0],
          ...<n>((x: N[n]) => N[n + 1]),
          (x: N.last) => R,
        ];
    
        function pipe<T>(init: T): T;
        function pipe<R, T, Ops>(init: T, ...ops: ...Ops<T, R>): R;

------
aabbcc1241
In my previous experience of "Svelte with Typescript", it merely remove the
typings, no type checking at all.

Try in below example, it print out '12' without type related error message.

<script lang="ts"> let a: number = '1'; let b: number = 2; </script>

<p> c = {a + b} </p>

~~~
cetra3
I've just tried this using the starter project they provide in the blog post,
and it does catch the error:

The error returned is `Type '"1"' is not assignable to type 'number'.`

~~~
aabbcc1241
Thanks for pointing out. It's getting better overtime! I missed the existence
of "svelte-check". I expected to see errors on the webpage like we usually see
from angular/react/stencil.

On svelte, the typescript error doesn't show up until you manually run svelte-
check.

------
JadoJodo
Slightly off-topic but I'm curious anyway: Has the tooling for JavaScript
improved with TypeScript's adoption? As a back-end developer, I feel like each
time I've tried to dig in and start a JavaScript project from scratch has
ended with me weeping after spending four hours fighting the tooling. Is there
a better way?

~~~
symlinkk
Just use create-react-app, it’s not hard.

~~~
crooked-v
I'd personally recommend Next.js instead. It's even more painless, seamlessly
handles a lot of other concerns (like routing), and can be used both as an SSR
server and to generate purely static HTML bundles.

------
aryonoco
Rich Harris (the creator of Svelte) just released a short 5 hour video course
on Svelte on Frontend Masters as well. It's great intro and touches most
common usecases and briefly introduces Sapper as well. If you already have a
FEM subscription, this is a great time to get into Svelte.

------
zamalek
I've been using Svelte TS for a pet project for maybe 2 weeks now. It's
fantastic. The VSCode plugin is also doing a great job.

I tried, and failed, to use Babel as the TS compiler - but TSC then Babel
works just fine.

------
untog
Very happy about this. I tried to combine the two a few months ago and it was
not a fun experience. Great to know I can give it another go now.

------
nojvek
Svelte is nice, but man I just want to use JSX. Don’t make me learn another
templating language.

~~~
wirahx
Svelte will never have JSX, not natively anyway. It's completely against the
philosophy.

Not all of us think JSX is a great thing. The "templating" language in Svelte
isn't really a templating language at all, it's just Javascript with some
(unavoidable) helpers. It takes about 2 minutes to learn since there are
really only maybe 5 helpers.

------
leejoramo
Unlike many who have not used Svelte due to lack of Typescript support, this
may give my team reason to consider Typescript.

------
zeroc8
Would love to use it, but I need something comparable to PrimeNG. Are there
any comprehensive UI toolkits out there already?

~~~
widgetic
Some - [https://awesomeopensource.com/project/ryanatkn/awesome-
svelt...](https://awesomeopensource.com/project/ryanatkn/awesome-svelte-
resources#ui-component-sets)

------
kylemh
Now I'm just waiting for some company to actually make an app with Sapper and
Svelte and I'll give this a go.

~~~
rawoke083600
Lol I've made two :)

[0][https://www.fibretiger.co.za](https://www.fibretiger.co.za) The above was
previously coded in angular 9. I've seen faster loads in CoreWebVitals, and
strangely... more of our post got featured in Google-Discover(could just be
coincidence)

[1][https://www.wepickflix.com](https://www.wepickflix.com)

------
fb03
I was literally searching for this like, a week ago. Glad to finally see it
land in a stable, first-class manner.

------
The_rationalist
How is Webstorm support with Svelte ?

~~~
mrath
I believe there is no official plugin for Svelte. So it may not be as good as
the support for React/Angular/Vue. But once Svelte is a bit more popular, I
think JetBrains will release a plugin.

------
heapslip
Just so you know svelte + typescript + eslint is currently not working.

------
drol3
Great news!

Was my only blocker :)

------
nXqd
Yes, finally.

