TS Compiler API:遍历给定类型的所有自定义属性

TS Compiler API : Traverse through all custom defined properties of a given type

对于以下模型结构,

interface Address{
   country: string;
}

interface Author{
  authorId: number;
  authorName:string;
  address: Address;
}

interface Book{
  bookId:string;
  title: string;
  author : Author;
}

我正在尝试遍历 Book 接口的所有属性。

const bookType = // get the type node of Book
const stack: any[] = [...bookType.getProperties()];
const props: any[] = [];

while (stack.length) {
  const prop = stack.pop();
  props.push(prop);
  if (checker.getTypeOfSymbolAtLocation(prop, node)) { //node is a ts.MethodDeclaration which returns a value of type Book
    stack.push(...checker.getTypeOfSymbolAtLocation(prop, node).getProperties());
  }
}

以上代码有效,但它也读取内置类型的属性,如字符串、数字等(toLocaleString、valueOf、toPrecision)。我想提取自定义 types/interfaces 的属性并忽略内置类型。

The above code works but it also reads the properties of in built types like string, number etc., ( toLocaleString, valueOf, toPrecision). I would like to extract the properties of custom types/interfaces and ignore the in built types.

这可以通过从类型到符号,然后检查符号是否链接回项目中找到的任何声明来实现。例如:

// untested, but something along these lines
const type = checker.getTypeOfSymbolAtLocation(prop, node);
const isTypeInYourPoject = type.getSymbol()?.getDeclarations()?.some(d => {
  // Or you could check the file path is not
  // in the `node_modules/typescript/lib` folder.
  return isFilePathInYourProject(d.getSourceFile().fileName);
});

if (isTypeInYourPoject) {
  // do stuff...
}

您还可以查看 type.flags 之类的内容来判断它是 string 还是 number.

之类的类型