Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 416
Interloper Avatar asked Dec 18 '25 10:12

Interloper


1 Answers

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());
like image 106
David Sherret Avatar answered Dec 21 '25 05:12

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!