2

Let's say we have the following code:

interface X<Y = any> {
  y: Y;
}

interface Z extends X<"why?"> {
  abc: "ABC";
}

/**
 *
 * Structurally, the `Z` type is...
 *
 * {
 *   y: "why?";
 *   abc: "ABC";
 * }
 *
 */

Is there any built-in mechanism for resolving the final type from a series of intertwined type and/or interface definitions? I can't find anything obvious from playing around with a typechecker and Type nodes.

Any advice would be greatly appreciated!

2
  • I'm not sure what your use case is, what exactly do you need to do? The full shape of the object is known at compile time, there's nothing special you have to do for that. If you're talking about runtime, that's a whole different (and much harder) question Commented Aug 3, 2020 at 20:09
  • @bugs that's incorrect: I do not want the shape at runtime. I want it at compile time. But I'd rather not traverse and stitch it together myself, given that the TS team has likely already implemented this (for the sake of structural type checking of course). Commented Aug 3, 2020 at 20:27

1 Answer 1

2

There's no public API for structural typing (see the Type Relationship API issue).

That said, you can get all the property names with types of the interface by doing the following:

const interfaceZDecl = sourceFile.statements[1] as ts.InterfaceDeclaration;
const type = checker.getTypeAtLocation(interfaceZDecl.name);

for (const prop of type.getProperties()) {
    console.log(`Name: ${prop.getName()}`);
    const propType = checker.getTypeOfSymbolAtLocation(prop, prop.valueDeclaration);
    console.log(`Type: ${checker.typeToString(propType)}`);
    console.log("---");
}

Outputs:

Name: abc
Type: "ABC"
---
Name: y
Type: "why?"
---
Sign up to request clarification or add additional context in comments.

Comments

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.