[英]Strange behaviour of callback function in Typescript
我正在嘗試解決 Typescript 中filter
數組 function 的問題,代碼如下:
type Tag = string
type Args = {
tags?: Tag[]
}
const func = async (args: Args) => {
if (args.tags) {
const entities = [
{ tagId: '1' },
{ tagId: '2' }
];
const filtered = entities.filter(entity => args.tags.includes(entity.tagId));
const mapped = args.tags.map(tag => tag + '_test');
}
};
此代碼拋出 TS2532 錯誤:當我嘗試過濾entities
數組時, Object 可能未定義。 由於某些原因,TS 解釋器認為args.tags
可以未定義,因此無法調用include
function。 但如您所見,上面有一個檢查, map
function 也可以正常工作。
這里有什么問題? 歡迎任何想法。
謝謝。
TypeScript 不知道filter
的回調會立即運行,因此如果例如filter
的回調稍后運行(假設在setTimeout
),則您的代碼將在這樣的調用下崩潰:
const a: Args = { tags: [] };
await func(a);
a.tags = undefined;
// Later, the callback runs and accesses 'includes' of the undefined we just set
你可以使用!
entity => args.tags!.includes ...
或將值存儲在const
const tags = args.tags;
if (tags) {
// ...
const filtered = entities.filter(entity => tags.includes ...
type Args = {
tags?: Tag[] // this means --> tags: Tag[] | undefined
}
在Array.filter()
使用可選鏈接和無效合並。
const filtered = entities.filter(entity => args?.tags?.includes(entity.tagId));
實體數組是一個對象數組,但 TypeScript 編譯器將類型推斷為any[]
並且不知道該對象將包含tagId
屬性。 您的代碼應該在運行時進行以下更改:
const entities: {tagId:string}[] = [
此外,您要考慮Args
類型中可能未定義的tags
屬性:
const filtered = entities.filter(entity => args.tags && args.tags.includes(entity.tagId));
完整代碼:
type Tag = string;
type Args = {
tags?: Tag[];
};
const func = async (args: Args) => {
if (args.tags) {
const entities: { tagId: string; }[] = [
{ tagId: '1' },
{ tagId: '2' }
];
const filtered = entities.filter(entity => args.tags && args.tags.includes(entity.tagId));
const mapped = args.tags.map(tag => tag + '_test');
}
};
我使用 ts-node 和 tsc (使用--lib es2016.array.include
)測試了這段代碼,沒有收到任何錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.