Skip to content

Commit

Permalink
feat: basic support for inferrable types (#1407)
Browse files Browse the repository at this point in the history
  • Loading branch information
swnf authored Dec 3, 2022
1 parent 49e6ab6 commit 62a17a9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
21 changes: 18 additions & 3 deletions src/NodeParser/InterfaceAndClassNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,27 @@ export class InterfaceAndClassNodeParser implements SubNodeParser {
}
return members;
}, [] as (ts.PropertyDeclaration | ts.PropertySignature | ts.ParameterPropertyDeclaration)[])
.filter((member) => isPublic(member) && !isStatic(member) && member.type && !isNodeHidden(member))
.filter((member) => isPublic(member) && !isStatic(member) && !isNodeHidden(member))
.reduce((entries, member) => {
let memberType: ts.Node | undefined = member.type;

// Use the type checker if the member has no explicit type
// Ignore members without an initializer. They have no useful type.
if (memberType === undefined && member.initializer !== undefined) {
const type = this.typeChecker.getTypeAtLocation(member);
memberType = this.typeChecker.typeToTypeNode(type, node, ts.NodeBuilderFlags.NoTruncation);
}

if (memberType !== undefined) {
return [...entries, { member, memberType }];
}
return entries;
}, [])
.map(
(member) =>
({ member, memberType }) =>
new ObjectProperty(
this.getPropertyName(member.name),
this.childNodeParser.createType(member.type!, context),
this.childNodeParser.createType(memberType, context),
!member.questionToken
)
)
Expand Down
13 changes: 10 additions & 3 deletions test/valid-data/class-single/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ export class MyObject {
public static staticProp: number;

public propA: number;
public propB: number;
// Test that types can be inferred
public propB = 42;

// Properties without type must be ignored
public noType;
Expand All @@ -17,8 +18,14 @@ export class MyObject {
readonly readonlyProp: string;

// Constructors must be ignored
public constructor(protected a: number, private b: number, c: number, public propC: number,
public propD?: string) {
public constructor(
protected a: number,
private b: number,
c: number,
// Test that types can be inferred
public propC = 42,
public propD?: string
) {
this.privateProp = false;
}

Expand Down

0 comments on commit 62a17a9

Please sign in to comment.