[英]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.