dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
5k stars 195 forks source link

Type references dont work #1568

Closed ofersadgat closed 2 months ago

ofersadgat commented 2 months ago

Describe the bug

Version: 23.0.0

I cannot resolve the type of an import to a concrete type. The type thats returned appears to always be 'any' regardless of what I do. Am I perhaps missing some initialization parameter?

To Reproduce

import { Project } from "ts-morph";

export const project = new Project({
    useInMemoryFileSystem: true,
    compilerOptions: {
        allowJs: true,
        jsx: ts.JsxEmit.ReactJSX,
        moduleResolution: ModuleResolutionKind.Bundler,
        esModuleInterop: true,
        resolveJsonModule: true,
        declaration: true,
        declarationMap: true,
    }
}); // or createProjectSync

console.log('project', project);

export const files: Record<string,string> = {
   '/MyClass.tsx': `
        import MyButton from 'MyButton';
        import {View} from 'react-native';

        export default function MyContainer(){
            return (
                <View>
                    <MyButton />
                    <MyButton />
                </View>
            );
        }
   `,
   '/MyButton.tsx': `
        import { Button } from 'react-native'; 
        export default function MyButton(){ 
            return ( 
                <Button title=\"abc123\" onPress={() => alert('pressed!')} /> 
            );
        };
   '/jsfile.d.ts': `
    export declare type MyComponentProps = {name: string};
    export declare function MyComponent(props: MyComponentProps): number; 
    `,
   '/jsfile.js': `
       export function MyComponent(props){ 
            return 5;
       };
   `,
};

const fileMap = Object.fromEntries(Object.entries(files).map(([file, data]) => {
    return [file, project.createSourceFile(file, data, {overwrite: true})];
}));
project.resolveSourceFileDependencies();

const myClassFile = fileMap['/MyClass.tsx'];
myClassFilefile.getImportDeclarations().forEach((importDeclaration) => {
                    const defaultImport = importDeclaration.getImportClause()?.getDefaultImport();
                    console.log('default import:', defaultImport, defaultImport && defaultImport.getType().getText());
                });

// I would expect the console log to output some type that isnt 'any'

Expected behavior

I would expect the actual types to be resolved across different files. (I've tried this for .ts -> .ts files and .js -> .d.ts files). Please ket me know if theres something I need to do to enable this sort of type resolution (including adding type resolution for .d.ts files from .js files). Thanks!

douglasg14b commented 1 month ago

How did you solve this? I see the issue is closed