I think this answer includes some excellent suggestions: always include your actual code in a code block/snippet in the post: the use of Stack Overflow should (ideally) not depend on the availability of external resources. Linking to the same code in the TypeScript Playground is recommended because of its rich interactive experience powered by IntelliSense and the TS Language Server: even with its limitations, it's a fantastic reproduction tool.
I want to provide an additional option: by including just a little boilerplate in a snippet: linking to a hosted transpiler script (e.g. @babel/standalone), you can actually include just the TypeScript source directly in a <script>
tag in the snippet HTML, and the compilation will happen client side, eliminating the need to include both source and compiled code in the post body, while still getting snippet output. Here's an example of what I mean:
TS Playground
<script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="typescript">
function add (numbers: number[]): number {
let sum = 0;
for (const n of numbers) sum += n;
return sum;
}
const sum = add([1, 2, 3, 4]);
console.log(sum); // 10
</script>
Even if unpkg (or other external transpiler script resource server) stops responding one day, the TS source code is still embedded in the post body.
This, of course, simply strips types from the source, so it won't include compiler-related diagnostic emits (they are styled in the playground as wavy underlines with tooltip-style information appearing in reaction to hovering):
To get that information in the snippet, you'd need to link and use the actual TypeScript compiler JS API, and those emits would need be visible somewhere in order to be useful in the post context. The snippet editor's virtual console is not really suited to display those kinds of messages, so I think type-stripping in a code snippet + linking to the TS Playground is a reasonable compromise to avoid a serious amount of boilerplate in every post (and a terrible first-load experience — unpkg reports the typescriptServices.js
script as being ~10.5 MB
in size). You can (and, ideally, should) also include any compiler diagnostic messages in additional static code blocks in the post body, like this:
const sum = add(1, 2, 3, 4); /*
~~~~~~~
Expected 1 arguments, but got 4.(2554) */
// Oops, that should have been a single array argument instead of serial numbers