簡體   English   中英

如何過濾打字稿中的對象數組,以便僅保留包含可選鍵的對象(並且知道打字稿)?

[英]How can I filter an array of objects in typescript such that only objects that contain an optional key are left (and typescript is aware)?

這與帶有嚴格空檢查的打字稿有關。 假設您有一個界面,例如:

interface Name {
  firstName?: string;
  lastName?: string;
}

並且您有一個Name[]數組。

如何以打字稿知道firstName存在的方式過濾此數組? 例如:

names.filter(name => !!name.firstName).map(name => {
  // inside here, typescript still thinks name.firstName is possibly undefined
  // but it should be aware that we have already filtered out elements with an
  // undefined firstName
})

filter接受可以作為類型防護的函數。 Typescript不會推斷函數的類型保護,但是您可以將返回類型顯式定義為類型保護:


interface Name {
  firstName?: string;
  lastName?: string;
}
declare const names: Name[];
names
    .filter((name): name is Name & { firstName: string } => !!name.firstName)
    .map(name => {
        name.firstName.big()
    });


上面我們定義了name參數為Name但是使用交集添加了firstName是必需的。 語法有點冗長,但可以。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM