Ts-morph: Cannot get properties of complex type

Created on 7 Jun 2021  路  5Comments  路  Source: dsherret/ts-morph

Describe the bug
I have a complex type where i can pass some "selection" to a function and this function will return subset type:
From https://stackoverflow.com/a/51968630/3021445

interface Data {
  one: string;
  two: number;
  three: {
    four: string;
    five: {
      six: Date;
    };
  };
}

declare const data: Data;

const result = select(data, { one: true, three: { five: { six: true } } }); 
// Here the "result" variable type will have all fields except "two" and "four"

I need to get "result" variable fields, but for some reason when i try to get type of "three" variable it becomes "any" type.

Version: 11.0.0

To Reproduce

I create codesandbox where you can play
https://codesandbox.io/s/goofy-diffie-owje4?file=/src/utils.ts:1470-1527

Expected behavior


I am able to get correct type object for complex types

question

All 5 comments

Do you get any diagnostics when calling project.getPreEmitDiagnostics()?

@dsherret i have empty array

@aspirisen sorry, I didn't see the all the files in the code sandbox. I will take a look at this soon.

@aspirisen ok, I'm not 100% sure what the correct way to use the typescript compiler API is, but I believe you need to use:

prop.getTypeAtLocation(declaration)

And always provide the node where the type node exists... for example do:

if (Node.isFunctionLikeDeclaration(declaration)) {
    const [param] = declaration.getParameters();
    const selection = getFieldSelection(param); // do param.getType() inside getFieldSelection
    return selection;
  }
}

...and always provide param to prop.getTypeAtLocation(param) within getFieldSelection. I have something very rough here: https://codesandbox.io/s/determined-liskov-4xk8c?file=/src/index.ts:40-115

@dsherret that's strange that what i tried didn't work correctly, it was able to get first level of type properties, but couldn't get nested properties.

Anyway, your solution works perfectly, thank you very much for help!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pierregallard picture pierregallard  路  4Comments

dyatko picture dyatko  路  3Comments

HoldYourWaffle picture HoldYourWaffle  路  4Comments

claudv picture claudv  路  3Comments

gregjacobs picture gregjacobs  路  4Comments