Hello TypeScript

See a TypeScript type checked at run time.

TJS is a typed JavaScript whose types survive to run time as checks. It can also take a TypeScript file and do the same with its annotations.

TypeScript checks the calls it can see. greet(42) is a compile error, but greet(42 as any) is not, and neither is greet(JSON.parse(text).name). Once the program runs, the string annotation is gone and nothing stops the number. The function does not crash, either: the template literal turns 42 into '42' and returns Hello, 42!. A crash gets reported; a plausible wrong string goes quietly into a page, a log or a database.

The example is a plain TypeScript function plus one comment that switches the checks on. The other two special comments, a doc comment and a test, are explained below.

/*#
`greet` builds a greeting from a name. TJS reads this block as
markdown documentation for the file.
*/

// By default TJS converts TypeScript the way tsc does: the types are
// erased. This line asks it to keep them as runtime checks:
/* @tjs TjsStrict */

/*test 'greet builds a greeting' {
  expect(greet('ts')).toBe('Hello, ts!')
}*/

function greet(name: string): string {
  return `Hello, ${name}!`
}

// A correct call works as usual
console.log(greet('World'))

// Compiled by tsc, this prints "Hello, 42!".
// Under TJS, greet returns an error value instead of a greeting.
// `bad` is typed `any` because the error has fields `string` lacks.
const bad: any = greet(42 as any)
console.log('Bad call result:', bad)

console.log('is an error:', bad instanceof Error)
console.log('path:', bad.path)
console.log('expected:', bad.expected, 'actual:', bad.actual)

What to look for in the output

The good call prints Hello, World!. The bad call does not print a greeting. It prints an error, whose first line reads:

Bad call result: MonadicError: Expected string for '<source>:14:greet.name', got number

The last three lines check what it is and read three of its fields:

is an error: true
path: <source>:14:greet.name
expected: string actual: number

What to notice