Created
September 15, 2017 15:25
-
-
Save danielrbradley/8f8ce339ebb209ee1a0791142b11be3d to your computer and use it in GitHub Desktop.
Testing JSON matches TypeScript types
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
import { writeFileSync, mkdirSync, existsSync } from 'fs' | |
import { resolve } from 'path' | |
import * as ts from 'typescript' | |
function checkForTypeErrors(jsonContent: string) { | |
const tempDir = resolve('.tmp') | |
const tempFilePath = resolve(tempDir, 'typecheck.ts') | |
if (!existsSync(tempDir)) { | |
mkdirSync(tempDir) | |
} | |
const tsContent = ` | |
import { Data } from '../type.test' | |
const data = <Data>${jsonContent}` | |
writeFileSync(tempFilePath, tsContent); | |
const program = ts.createProgram([tempFilePath], { | |
noEmit: true, | |
strictNullChecks: true, | |
lib: [ "es5", "es6" ], | |
target: ts.ScriptTarget.ES2016 | |
}); | |
const result = program.emit(); | |
const allErrors = ts.getPreEmitDiagnostics(program).concat(result.diagnostics) | |
return allErrors.filter(e => e.file && e.file.fileName === tempFilePath) | |
} | |
export interface Data { | |
id: string | |
count: number | |
} | |
it('passes when matches', () => { | |
const errors = checkForTypeErrors( | |
`{ | |
"id": "my id", | |
"count": 123 | |
}` | |
) | |
expect(errors.length).toEqual(0) | |
}) | |
it('highlights type mismatch', () => { | |
const errors = checkForTypeErrors( | |
`{ | |
"id": 123, | |
"name": "test" | |
}` | |
) | |
expect(errors.length).toEqual(1) | |
expect(ts.flattenDiagnosticMessageText(errors[0].messageText, '\n')).toEqual( | |
`Type '{ \"id\": number; \"name\": string; }' cannot be converted to type 'Data'. | |
Types of property 'id' are incompatible. | |
Type 'number' is not comparable to type 'string'.`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment