Skip to content

Instantly share code, notes, and snippets.

@gpoitch
Last active April 3, 2020 16:29
Show Gist options
  • Save gpoitch/4d003c38b6066978ce6b4acbb3cd45f6 to your computer and use it in GitHub Desktop.
Save gpoitch/4d003c38b6066978ce6b4acbb3cd45f6 to your computer and use it in GitHub Desktop.
Typescript type checking test assertions
const ts = require('typescript')
const DefaultOptions = {
noEmit: true,
target: ts.ScriptTarget.ES2019,
module: ts.ModuleKind.CommonJS
}
function typecheck(filepath, options = DefaultOptions) {
const program = ts.createProgram([filepath], options)
const emitResult = program.emit()
const diagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics)
return formatDiagnostics(diagnostics)
}
function formatDiagnostics(diagnostics) {
return diagnostics.map((diagnostic) => {
const { messageText: info, file } = diagnostic
const result = {
message: info.messageText,
category: info.category,
code: info.code
}
if (file) {
const { line, character } = file.getLineAndCharacterOfPosition(diagnostic.start)
result.file = file.fileName
result.line = line + 1
result.character = character + 1
}
return result
})
}
module.exports = { typecheck }
interface Foo {
bar: string
baz?: number
}
const foo: Foo = {
bar: 1,
baz: 'baz',
qux: null
}
const { strictEqual } = require('assert')
const { describe, it } = require('mocha')
const { typecheck } = require('./typecheck')
describe('Type checking assertions', () => {
it('Should fail with an invalid file', () => {
const errors = typecheck('./input.ts')
strictEqual(errors.length, 3)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment