簡體   English   中英

Typescript object 數組類型聲明中的可空鍵

[英]Typescript nullable keys in object array type declaration

我正在使用 Typescript 來編寫 React 組件。 目前我將道具類型定義為 Typescript type 這是一個例子:

type Props = {
  id: number //required
  name: string | null //optional
}

type ParentProps = Array<Props>

let props:ParentProps = [
  {
      id:5,
      name:"new"
  },
  {
      id:7,
  }
]

//Gives error: Property 'name' is missing in type '{ id: number; }' but required in type 'Props' 

在這種情況下,我希望ParentProps type只是Props type的數組。 在實踐中,可為空的名稱鍵適用於Prop類型的單個對象。 當聲明一個ParentProps類型的 object 時,它給出了上面的代碼片段。

為了與更簡單的組件保持一致,我寧願繼續使用type來定義組件道具,而不是接口。 有人對如何聲明類型以定義允許某些 null 鍵的類型對象數組有任何建議嗎?

謝謝你。

如何通過以下方式定義Props

type Props = {
  id: number
  name?: string | null
}

要不就

type Props = {
  id: number
  name?: string
}

此外,如果您想保持Props定義不變,您可以更改type ParentProps

type ParentProps = Array< Omit<Props, "name"> & { name?: string|null } >

暫無
暫無

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

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