Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: basic support for inferrable types #1407

Merged
merged 1 commit into from
Dec 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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