Typescript factory create interface from function return type

83 Views Asked by At

How can signature or ts.Type extracted from the AST be passed into the factory method for reuse? The ulitmate goal is to take a return type of a function and create an interface for it.

 import * as ts from "typescript";


 const signature = typeChecker.getSignatureFromDeclaration(node);
 const retType = signature?.getReturnType();

 ts.factory.createInterfaceDeclaration(
   undefined,
   "interfaceName",
   undefined,
   undefined,
   //How to pass the extracted signature from above inside here?
   [retType]
);

If it is necessary to traverse the tree how to get the SyntaxKind?

const properties = retType.getProperties();
properties.map((property) => {
  const propertyName = property.getName();
  const valueDeclaration = property.valueDeclaration;
  const typeOfParameter = typeChecker.getTypeOfSymbol(property);

  const questionToken = undefined;
  //   const questionToken =
  //     valueDeclaration !== undefined
  //       ? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
  //       : undefined;

  //TODO how to get those?
  const keywordTypeNode = ts.factory.createKeywordTypeNode(
    ts.SyntaxKind.NumberKeyword
  );

  ts.factory.createPropertySignature(
    undefined,
    propertyName,
    questionToken,
    keywordTypeNode
  );
});
0

There are 0 best solutions below