Created
October 16, 2018 06:06
-
-
Save maolion/bd4fd727f94e6f89b552d0f9cee56424 to your computer and use it in GitHub Desktop.
type check
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 * as FS from 'fs'; | |
import { | |
LanguageServiceHost, | |
ScriptSnapshot, | |
createDocumentRegistry, | |
createLanguageService, | |
flattenDiagnosticMessageText, | |
getDefaultLibFilePath, | |
} from 'typescript'; | |
/** | |
* @param object An object that can be serialized to JSON. | |
*/ | |
export function checkObjectTypeErrors( | |
object: any, | |
typeFileName: string, | |
typeName: string, | |
): string[] | undefined { | |
let json = JSON.stringify(object); | |
let typeFileContent = FS.readFileSync(typeFileName); | |
let validationContent = `${typeFileContent}\nconst _: ${typeName} = ${json};`; | |
return checkTypeErrors(validationContent); | |
} | |
function checkTypeErrors(content: string): string[] | undefined { | |
const scriptFileName = '_.ts'; | |
const serviceHost: LanguageServiceHost = { | |
getScriptFileNames() { | |
return [scriptFileName]; | |
}, | |
getScriptVersion() { | |
return '0'; | |
}, | |
getScriptSnapshot(fileName) { | |
if (fileName === scriptFileName) { | |
return ScriptSnapshot.fromString(content); | |
} else { | |
try { | |
return ScriptSnapshot.fromString(FS.readFileSync(fileName, 'utf-8')); | |
} catch (error) { | |
return undefined; | |
} | |
} | |
}, | |
getCurrentDirectory() { | |
return __dirname; | |
}, | |
getCompilationSettings() { | |
return { | |
strict: true, | |
noEmit: true, | |
}; | |
}, | |
getDefaultLibFileName(options) { | |
return getDefaultLibFilePath(options); | |
}, | |
}; | |
const languageService = createLanguageService( | |
serviceHost, | |
createDocumentRegistry(), | |
); | |
let diagnostics = [ | |
...languageService.getSyntacticDiagnostics(scriptFileName), | |
...languageService.getSemanticDiagnostics(scriptFileName), | |
]; | |
if (!diagnostics.length) { | |
return undefined; | |
} | |
return diagnostics.map(diagnostic => | |
flattenDiagnosticMessageText(diagnostic.messageText, '\n'), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment