TypeScript compiler API get get type of mapped property

Viewed 463

Given type Mapping = Record<'success' | 'error', React.ReactNode>. How do I get the typescript.Type using the compiler API?

The symbol of Mapping has two properties as expected but each property symbol does not have a type.

In { success: React.ReactNode, error: React.ReactNode } you could get the type for each property by using checker.getTypeOfSymbolAtLocation(symbol, symbol.declarations[0]) but this doesn t seem to work for mapped types

1 Answers

This works when providing either the name or type node of the type alias for the node argument of TypeChecker#getTypeOfSymbolAtLocation(symbol, node):

const mappingDec = sourceFile.statements[0] as ts.TypeAliasDeclaration;
const mappingType = typeChecker.getTypeAtLocation(mappingDec.name);

// then example use...
for (const prop of mappingType.getProperties()) {
    const name = prop.getName();
    const type = typeChecker.getTypeOfSymbolAtLocation(prop, mappingDec.name)
}
Related