Skip to content

Commit f715f25

Browse files
committed
Convert functional interfaces to function types (closes bensku#2)
1 parent 399fa10 commit f715f25

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/main/java/io/github/bensku/tsbind/AstGenerator.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,11 @@ private boolean isPublic(TypeDeclaration<?> type, BodyDeclaration<?> member) {
279279
}
280280

281281
private boolean isPublic(ResolvedReferenceTypeDeclaration type) {
282+
// Special case for functional interfaces that are converted to function types
283+
// (you obviously can't extend those in TypeScript)
284+
if (type.isFunctionalInterface()) {
285+
return false;
286+
}
282287
if (type instanceof HasAccessSpecifier) {
283288
return ((HasAccessSpecifier) type).accessSpecifier() == AccessSpecifier.PUBLIC;
284289
}

src/main/java/io/github/bensku/tsbind/binding/TsClass.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,22 @@ public void emit(TypeDefinition node, TsEmitter out) {
282282
node.javadoc.ifPresent(out::javadoc);
283283
// Class declaration, including superclass and interfaces
284284

285+
// Transform functional interfaces into function signatures
286+
// For now, only do this if there are no (static) methods or fields
287+
if (node.kind == TypeDefinition.Kind.INTERFACE
288+
&& node.interfaces.isEmpty() && node.superTypes.isEmpty()
289+
&& node.members.size() == 1) {
290+
Member member = node.members.get(0);
291+
if (!member.isStatic && member instanceof Method) {
292+
out.print("export type ");
293+
emitName(node.ref.simpleName(), node.ref, out);
294+
out.print(" = ");
295+
emitFunction((Method) member, out);
296+
out.println(";");
297+
return;
298+
}
299+
}
300+
285301
out.print("export class ");
286302
emitName(node.ref.simpleName(), node.ref, out);
287303

@@ -341,5 +357,12 @@ private void emitName(String name, TypeRef type, TsEmitter out) {
341357
out.print("<").print(((TypeRef.Parametrized) type).typeParams(), ", ").print(">");
342358
}
343359
}
360+
361+
private void emitFunction(Method method, TsEmitter out) {
362+
out.print("(");
363+
out.print(method.params, ", ");
364+
out.print(") => ");
365+
out.print(method.returnType);
366+
}
344367

345368
}

0 commit comments

Comments
 (0)