TypeScript Compiler API: how to get literal value by ImportSpecifier node?

589 Views Asked by At

I have two TypeScript files.

Const.ts:

export const defaultProps = {
    name: 'Node'
};

MyComponent.tsx:

import * as React from 'react';
import {defaultProps} from './const';

interface MyCompProps {
  name: string;
}

export class MyComp extends React.Component<MyCompProps> {
  static defaultProps = defaultProps;

  constructor(props: MyCompProps) {
    super(props);
  }

  render() {
    const {name} = this.props;
    return <div>{name}</div>;
  }
}

I am using TypeScript compiler API for parsing these files. I'm interested in the line:

static defaultProps = defaultProps;

In right side I have node with kind=265 (ImportSpecifier). How to get from it node with literal value of object? Using the method checker.getSymbolAtLocation(node) returns undefined.

1

There are 1 best solutions below

1
On BEST ANSWER

Instead of getting the symbol of the import specifier, it works to get the symbol of the import specifier's name (the identifier). This will just be the local symbol inside MyComponent.tsx though, so from there you will need to get the aliased symbol which in this case will lead you to the defaultProps variable declaration in const.ts:

const symbol = checker.getSymbolAtLocation(importSpecifier.name)!;
const aliasedSymbol = checker.getAliasedSymbol(symbol);
const varDecl = aliasedSymbol.getDeclarations()![0];

// outputs the `defaultProps` variable declaration
console.log(varDecl.getText());