diff --git a/src/generator.ts b/src/generator.ts index 7c2cda76..a11fcc7d 100644 --- a/src/generator.ts +++ b/src/generator.ts @@ -186,6 +186,7 @@ function generateInterface( .map(({ isRequired, keyName, ast }) => [isRequired, keyName, ast, generateType(ast, options)] as [boolean, string, AST, string]) .map(([isRequired, keyName, ast, type]) => (hasComment(ast) && !ast.standaloneName ? generateComment(ast.comment) + '\n' : '') + + (options.readOnlyProperties === true ? 'readonly ' : '') + escapeKeyName(keyName) + (isRequired ? '' : '?') + ': ' diff --git a/src/index.ts b/src/index.ts index 11c2ff17..7d26d58e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,6 +44,10 @@ export interface Options { * [$RefParser](https://github.com/BigstickCarpet/json-schema-ref-parser) Options, used when resolving `$ref`s */ $refOptions: $RefOptions + /** + * Generate interfaces with read-only (immutable) properties. + */ + readOnlyProperties: boolean } export const DEFAULT_OPTIONS: Options = { @@ -66,7 +70,8 @@ export const DEFAULT_OPTIONS: Options = { useTabs: false }, unreachableDefinitions: false, - $refOptions: {} + $refOptions: {}, + readOnlyProperties: false } export function compileFromFile( diff --git a/test/__snapshots__/test/test.ts.md b/test/__snapshots__/test/test.ts.md index f47d0f65..670a01a6 100644 --- a/test/__snapshots__/test/test.ts.md +++ b/test/__snapshots__/test/test.ts.md @@ -8775,3 +8775,20 @@ Generated by [AVA](https://ava.li). [k: string]: any;␊ }␊ ` + +## readonlyProperties.js + +> Snapshot 1 + + `/* tslint:disable */␊ + /**␊ + * This file was automatically generated by json-schema-to-typescript.␊ + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,␊ + * and run json-schema-to-typescript to regenerate this file.␊ + */␊ + ␊ + export interface ReadOnlyExample {␊ + readonly foo: string;␊ + readonly bar: number;␊ + }␊ + ` diff --git a/test/__snapshots__/test/test.ts.snap b/test/__snapshots__/test/test.ts.snap index 17d3b93f..1843e1ff 100644 Binary files a/test/__snapshots__/test/test.ts.snap and b/test/__snapshots__/test/test.ts.snap differ diff --git a/test/e2e/readonlyProperties.ts b/test/e2e/readonlyProperties.ts new file mode 100644 index 00000000..3c1f1aca --- /dev/null +++ b/test/e2e/readonlyProperties.ts @@ -0,0 +1,20 @@ +import { Options } from '../../src/' + +export const input = { + title: 'ReadOnlyExample', + type: 'object', + properties: { + foo: { + type: 'string' + }, + bar: { + type: 'number' + } + }, + required: ['foo', 'bar'], + additionalProperties: false +} + +export const options: Partial = { + readOnlyProperties: true +}