Skip to content

Commit

Permalink
fix(plugin): fix optional props in strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Feb 18, 2020
1 parent 2f7e228 commit c271871
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
24 changes: 24 additions & 0 deletions lib/plugin/utils/plugin-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ export function getTypeReferenceAsString(
if (text === Date.name) {
return text;
}
if (isAutoGeneratedUnion(type)) {
return getTypeReferenceAsString(
type.types[type.types.length - 1],
typeChecker
);
}
if (
text === 'any' ||
text === 'unknown' ||
Expand Down Expand Up @@ -138,3 +144,21 @@ export function replaceImportPath(typeReference: string, fileName: string) {
export function isDynamicallyAdded(identifier: ts.Node) {
return identifier && !identifier.parent && identifier.pos === -1;
}

/**
* when "strict" mode enabled, TypeScript transform the type signature of optional properties to
* the {undefined | T} where T is the original type. Hence, we have to extract the last type of type union
* @param type
*/
export function isAutoGeneratedUnion(
type: ts.Type
): type is ts.UnionOrIntersectionType {
if (type.isUnionOrIntersection() && !isEnum(type)) {
if (type.types && type.types.length === 2) {
if (type.types.some((type: any) => type.intrinsicName === 'undefined')) {
return true;
}
}
}
return false;
}
2 changes: 1 addition & 1 deletion test/plugin/fixtures/create-cat-alt.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class CreateCatDto2 {
age: number = 3;
tags: string[];
status: Status = Status.ENABLED;
readonly breed?: string;
readonly breed?: string | undefined;
nodes: Node[];
alias: AliasedType;
numberAlias: NumberAlias;
Expand Down

0 comments on commit c271871

Please sign in to comment.