Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition for tsconfig.json

Tags:

typescript

I want to write code in Typescript that generates a tsconfig.json file from a runtime object. Where can I get the definition for this object, e.g. something like the following:

interface TSConfig [
    compileOnSave?: boolean;
    files?: string[];
}
like image 693
Zev Spitz Avatar asked Jun 03 '26 06:06

Zev Spitz


1 Answers

You can reuse some of the types defined in the typescript module (you can get it via npm install typescript) for compiler options and type acquisition options, although there is no type defined for the full tsconfig.json, and we need to do some conditional type magic (available in typescript 2.8) to get the type for compiler options. The enums are exported, so you can just use them directly.

import * as ts from 'typescript' // Import will be elided as long as we only use types from it, so we don't have the compiler code  loaded at runtime

type CompilerOptions = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ? 
    TResult extends { options: infer TOptions } ? TOptions : never : never;
type TypeAcquisition = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ? 
    TResult extends { typeAcquisition?: infer TTypeAcquisition } ? TTypeAcquisition : never : never;

interface TsConfig {

    compilerOptions: CompilerOptions;
    exclude: string[];
    compileOnSave: boolean;
    extends: string;
    files: string[];
    include: string[];
    typeAcquisition: TypeAcquisition
}

Note This has the advantage that changes made to the CompilerOptions and TypeAcquisition types by the compiler team will be reflected in your code when you update the package. The disadvantage is that it extracts some types from the compiler API which probably were not directly exposed for a reason (although since they are part of the result of ts.parseCommandLine if the compiler team would change them, it would be a breaking API change)

like image 166
Titian Cernicova-Dragomir Avatar answered Jun 05 '26 01:06

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!