2

I wanted to check whether a ClassDeclaration of a file a.ts implements an InterfaceDeclaration from a file b.ts using Compiler API. But I couldn't find a method or a function for it.

function isClassImplementInterface(
  ts.ClassDeclaration: classDeclaration,
  ts.InterfaceDeclaration: interfaceDeclaration
): boolean {
  // return true if classDeclaration implements interfaceDeclaration correctly
}

Is there any function for it out of Compiler API?

3
  • 1
    You can use checker.isTypeAssignableTo after you get the types of the class and the interface declaration. Commented Dec 29, 2019 at 12:19
  • @TitianCernicova-Dragomir that's internal API so it can't be used. See the GitHub issue here. Commented Dec 29, 2019 at 17:27
  • @DavidSherret Wops, my bad, thought that ways part of the public api Commented Dec 29, 2019 at 18:18

1 Answer 1

4

To check if a class directly implements a certain interface you can look at the types of the implements heritage clause.

For example:

function doesClassDirectlyImplementInterface(
    classDec: ts.ClassDeclaration,
    interfaceDec: ts.InterfaceDeclaration,
    typeChecker: ts.TypeChecker
) {
    const implementsClause = classDec.heritageClauses
        ?.find(c => c.token === ts.SyntaxKind.ImplementsKeyword);

    for (const clauseTypeNode of implementsClause?.types ?? []) {
        const clauseType = typeChecker.getTypeAtLocation(clauseTypeNode);
        if (clauseType.getSymbol()?.declarations.some(d => d === interfaceDec))
            return true;
    }

    return false;
}

You may want to expand on that to also check if the class declaration has a base class and then check that class' heritage clauses as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, the above code will be a great help. I'll try to make a utility code based on your guide. Thanks ! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.