![Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility](https://cdn.sanity.io/images/cgdhsj6q/production/97774ea8c88cc8f4bed2766c31994ebc38116948-1664x1366.png?w=400&fit=max&auto=format)
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
literate-ts
Advanced tools
Literate TS statically checks TypeScript code samples in written text (blog posts, books, etc.). It was developed and used to type check Effective TypeScript (O'Reilly 2019) as well as the companion blog, effectivetypescript.com.
$ npm install -D typescript literate-ts
$ literate-ts path/to/posts/*.md
TypeScript is a peer dependency of literate-ts, so you'll need to install it yourself. It's done this way so that you're in control of the TypeScript version. (Checking for breakages when you update TS is one of the main uses cases of literate-ts.)
Literate TS checks three sorts of things.
Expected errors. To assert the existence of an error, use a comment with a squiggly underscore in it:
let str = 'not a number';
let num: number = str;
// ~~~ Type 'string' is not assignable to type 'number'.
Literate TS will verify that this error occurs in your code sample, and no others. In other words, with no error annotations, literate-ts verifies that there are no errors.
Types. To assert that the type of an expression is what you expect, use a comment starting with "type is":
'four score'.split(' '); // type is string[]
Literate TS will verify that the type is precisely what you specify textually, ala dtslint.
You can also use twoslash syntax for type assertions:
const parts = 'four score'.split(' ');
// ^? const parts: string[]
Output. To assert the output of a code sample, give it an ID and include a paired one ending
with -output
. In Asciidoc, for example:
[[sample]]
[source,ts]
----
console.log('Hello');
----
[[sample-output]]
....
Hello
....
Literate TS will convert your code sample to JavaScript, run it through Node and diff the output. You can use this to create something like a unit test for your code samples.
You ran your code samples through the TypeScript playground when you wrote them. Why bother spending the time writing just the right set of directives and comments to get them running through literate-ts?
I wondered this myself while writing Effective TypeScript, but eventually this tool demonstrated its value many times over.
The arguments for using it are similar to those for writing tests or using TypeScript itself:
Safe refactoring editing Your code samples type checked when you wrote them. But then you,
your co-author or your editor went and changed things. Maybe you renamed a variable or function
in one sample and didn't update it in subsequent samples. Maybe you deleted the definition of a
function that you referenced later. Literate TS found a few errors the first time through
Effective TypeScript, but I can't recall a single edit I made that didn't trigger a
verification failure.
Damage control with new TypeScript releases As Anders has said, semantic versioning in TypeScript is pretty meaningless because the whole point of new releases is to break your code (or, rather, to reveal that it was already broken). When the next TypeScript release comes out, are you going to re-run all your code samples through it? With Literate TS this is easy. For reference, TypeScript 3.8 broke two of the 600 samples in Effective TypeScript. I fixed them and did a new release. Nothing broke with TypeScript 3.9. In both cases, it was a tremendous relief to know exactly what the damage was, or to know that there was no damage at all.
Completeness. You ran your code samples through TypeScript, but did you actually run all of them? Maybe you forgot one. Literate TS won't! Even the process of figuring out which code samples need to be prepended to others to form a valid compilation unit is helpful. If you can't create one, or the sequence is too elaborate, then something's probably wrong.
Practicing what you preach If you're writing a book or blog about TypeScript, you're probably already bought into the value of static analysis. Doing static analysis on your book is very much in the spirit of TypeScript!
literate-ts supports both Asciidoc and Markdown sources. The syntax used for each is slightly different.
Only fenced code blocks are supported in Markdown sources. For a source to be checked, it needs to have its language marked as "ts" or "js":
Here's a TypeScript code sample:
```ts
let num = 10; // type is number
```
To give a code sample an ID, use an HTML comment starting with a #
:
This sample has an ID of `Point`:
<!-- #Point -->
```ts
type Point = [number, number];
```
To pass a directive to the verifier, e.g. to tell it to concatenate sources, add an HTML comment
starting with verifier:
immediately before the sample. For example:
We can define a type using `interface`:
<!-- verifier:prepend-to-following -->
```ts
interface Student {
name: string;
age: number;
}
```
And then create objects of that type:
```ts
const student: Student = { name: 'Bobby Droppers', age: 12 };
```
You may also use // #id
or // verifier:directive
as an alternative form.
This is primarily useful if you want to prepend a code sample that's hidden inside an
HTML comment.
See below for a complete list of directives.
Asciidoc is a bit like Markdown, but more flexible and complicated. In particular O'Reilly uses it in their Atlas publishing system. Any recent O'Reilly book (including Effective TypeScript) is written in Asciidoc. GitHub also provides a rich display for Asciidoc source files.
In Asciidoc, code samples are marked with ----
or ....
. Samples must be marked
with [source,ts]
to be checked, or [source,js]
to be run through Node.
Code samples can be given an identifier using [[id]]
:
This sample has an ID of `point`:
[[point]]
[source,ts]
----
type Point = [number, number];
// ^? type Point = [number, number]
----
Directives begin with // verifier
. For example:
// verifier:prepend-to-following
[source,ts]
----
interface Student {
name: string;
age: number;
}
----
[source,ts]
----
const student: Student = { name: 'Bobby Droppers', age: 12 };
----
See below for a complete list of directives.
See above for how to give directive to literate-ts in your source format.
Sometimes you don't want to show the full implementation of a function. For example:
function computeSHA512(text: string): number {
// ...
}
The implementation is hidden, but unfortunately so is the return
statement, which means that
this won't type check (tsc
complains that it returns void
but is declared to return number
).
Literate TS supports this through "replacements": if you give the code sample an ID of sha512
(see above for how to do this in Markdown and Asciidoc formats) then you can put something like
this in a file called sha512.ts
:
function computeSHA512(text: string): number {
// COMPRESS
return 0;
// END
}
Obviously this isn't a real implementation but it will make the type checker happy. You tell
Literate TS about this by passing a replacements
directory via the -r
flag:
$ literate-ts -r path/to/replacements path/to/posts/*.md
The correspondence between replacements and their sources is checked and must be precise. In
addition to COMPRESS...END
, you can also use HIDE...END
to completely remove code. Of course,
be careful not to mislead the reader when you do this.
(This syntax comes from pyliterate.)
If you'd like to keep your source files self-contained, you can put the replacement in a code block and reference it with a replace-with-id
directive. See this sample file for examples.
--help
: Show help.--version
: Show version numbers for literate-ts
and typescript
.=-f
/--filter
: Only check IDs with the given prefix.-r
/--replacements
: If specified, load **/*.{ts,js,txt}
under this directory as additional sources.--alsologtostderr
: Log to stderr in addition to a log file.--nocache
: Disable reading and writing from on-disk cache. If this results in different behavior, please file an issue. The cache is in node_modules/.cache/literate-ts
. Delete this directory to clear the cache.It's extremely convenient to run literate-ts as a task in VS Code since it will show errors inline in your document. You need to set up a task with an appropriate problemMatcher
to make this work. Add the following to your tasks.json
(change yarn
to another package manager as needed):
{
"label": "Run file through literate-ts",
"command": "yarn",
"args": [
"literate-ts",
"${file}",
],
"presentation": {
"echo": true,
"reveal": "never",
"revealProblems": "onProblem",
"close": true,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"problemMatcher": [
{
"owner": "literate-ts",
"fileLocation": "absolute",
"pattern": [
{
"regexp": "^💥 (.*?):(\\d+):(\\d+)-(\\d+): (.*)$",
"file": 1,
"line": 2,
"column": 3,
"endColumn": 4,
"message": 5,
}
]
},
{
"owner": "literate-ts",
"fileLocation": "absolute",
"pattern": {
"regexp": "^💥 (.*?):(\\d+): (.*)$",
"file": 1,
"line": 2,
"message": 3
}
}
]
}
Quickstart:
$ yarn
$ yarn ts-node index.ts examples/asciidoc/sample.asciidoc
Logging details to /var/folders/st/8n5l6s0139x5dwpxfhl0xs3w0000gn/T/tmp-96270LdwL51L23N9D/log.txt
Verifying with TypeScript 3.6.2
examples/asciidoc/sample.asciidoc 5/5 passed
✓ sample-6
✓ sample-17
✓ sample-25
✓ sample-32
✓ sample-41
✓ All samples passed!
✨ Done in 9.24s.
Publish a new version:
$ vim package.json # update version
$ yarn test
$ tsc
$ npm publish
FAQs
Code samples that scale
The npm package literate-ts receives a total of 2 weekly downloads. As such, literate-ts popularity was classified as not popular.
We found that literate-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.