如何從變數的型別列印完整的屬性樹?讓我們看下面的例子,
interface Address{
country: string;
}
interface Author{
authorId: number;
authorName:string;
address: Address;
}
interface Book{
bookId:string;
title: string;
author : Author;
}
我的代碼中的一個方法回傳一個型別的值,Book我使用checker.getReturnTypeOfSignature(methodSignature!). 現在從這種型別,我需要創建屬性樹,如,
[
'bookId',
'title',
'author.authorId',
'author.authorName',
'author.address.country'
]
我嘗試使用以下代碼遍歷屬性樹,
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)。我想提取自定義型別/介面的屬性并忽略內置型別。
uj5u.com熱心網友回復:
上面的代碼有效,但它也讀取內置型別的屬性,如字串、數字等(toLocaleString、valueOf、toPrecision)。我想提取自定義型別/介面的屬性并忽略內置型別。
這可以通過從型別到符號,然后檢查符號是否鏈接回專案中找到的任何宣告來實作。例如:
// 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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387146.html
上一篇:如何處理打字稿中的狀態?
