我正在嘗試解決filterTypescript 中陣列函式的問題,代碼如下:
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。由于某些原因,TS 解釋器認為args.tags可以是未定義的,因此include無法呼叫函式。但是如您所見,上面有一個檢查,該map功能也可以正常作業。
這里有什么問題?歡迎任何想法。
謝謝。
uj5u.com熱心網友回復:
TypeScript 不知道filter的回呼會立即運行,因此如果例如filter的回呼稍后運行(假設在 a 上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 ...
uj5u.com熱心網友回復:
type Args = {
tags?: Tag[] // this means --> tags: Tag[] | undefined
}
在內部使用可選鏈接和無效合并Array.filter()。
const filtered = entities.filter(entity => args?.tags?.includes(entity.tagId));
uj5u.com熱心網友回復:
物體陣列是一個物件陣列,但 TypeScript 編譯器將型別推斷為any[]并且不知道該物件將包含該tagId屬性。您的代碼應該在運行時進行以下更改:
const entities: {tagId:string}[] = [
此外,您要考慮型別中可能未定義的tags屬性Args:
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)測驗了這段代碼,沒有收到任何錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326530.html
標籤:javascript 打字稿
