Last active
April 3, 2020 16:29
-
-
Save gpoitch/4d003c38b6066978ce6b4acbb3cd45f6 to your computer and use it in GitHub Desktop.
Typescript type checking test assertions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Foo { | |
bar: string | |
baz?: number | |
} | |
const foo: Foo = { | |
bar: 1, | |
baz: 'baz', | |
qux: null | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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