Skip to content

Commit

Permalink
feat: Add WriterFunctions.assertion.
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret committed May 15, 2019
1 parent cfce40b commit 37c875e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/ts-morph.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1928,6 +1928,10 @@ export declare class WriterFunctions {
* Gets a writer function for writing an intersection type.
*/
static intersectionType(firstType: WriterFunctionOrValue, secondType: WriterFunctionOrValue, ...additionalTypes: WriterFunctionOrValue[]): (writer: CodeBlockWriter) => void;
/**
* Gets a writer function for writing a type assertion (ex. `type as assertionType`).
*/
static assertion(type: WriterFunctionOrValue, assertionType: WriterFunctionOrValue): (writer: CodeBlockWriter) => void;
}

export declare type WriterFunctionOrValue = string | number | WriterFunction;
Expand Down
9 changes: 9 additions & 0 deletions src/structurePrinters/WriterFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@ export class WriterFunctions {
static intersectionType(firstType: WriterFunctionOrValue, secondType: WriterFunctionOrValue, ...additionalTypes: WriterFunctionOrValue[]) {
return getWriteFunctionForUnionOrIntersectionType("&", [firstType, secondType, ...additionalTypes]);
}

/** Gets a writer function for writing a type assertion (ex. `type as assertionType`). */
static assertion(type: WriterFunctionOrValue, assertionType: WriterFunctionOrValue) {
return (writer: CodeBlockWriter) => {
writeValue(writer, type);
writer.spaceIfLastNot().write("as ");
writeValue(writer, assertionType);
};
}
}

function getWriteFunctionForUnionOrIntersectionType(separator: "|" | "&", args: WriterFunctionOrValue[]) {
Expand Down
10 changes: 10 additions & 0 deletions src/tests/structurePrinters/writerFunctionsTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,14 @@ describe(nameof<WriterFunctions>(), () => {
doWriterTest((writer, { intersectionType }) => intersectionType("C", "A", w => w.write("5"), 7)(writer), "C & A & 5 & 7");
});
});

describe(nameof(WriterFunctions.assertion), () => {
it("should write when specifying writer functions", () => {
doWriterTest((writer, { assertion }) => assertion(w => w.write("a"), w => w.write("b"))(writer), "a as b");
});

it("should write when specifying strings", () => {
doWriterTest((writer, { assertion }) => assertion("a", "b")(writer), "a as b");
});
});
});

0 comments on commit 37c875e

Please sign in to comment.