我來自 JS 背景,現在正在學習 Typescript。我無法克服這個問題。我有一個非常特別的型別狀態,我知道我將來需要使用它:
type NotificationValuesType = {
channel: string
for: NotificationUsageTypes
id: string
type: NotificationTypes
workspace: string
}[]
我正在像這樣設定我的 React 狀態:
const [dropdownsState, setDropdownsState] = useState<NotificationValuesType>([])
問題是,一開始我現在只能type和id所有道具的其余部分,我可以在某些時候收集直通一系列下拉選單中,當用戶選擇他們,事件觸發,然后填充在同一時間與一個下拉的狀態,所以,它將只是:
[{id: "id", type: "type", channel: "channel"}]
在下一個事件中,將再進行[{id: "id", type: "type", channel: "channel", workspace: "workspace"}]一步和狀態更新以了解宣告型別中的所有道具。
我不明白的是如何告訴 Typescript 在我知道所有道具之前停止對我大喊大叫,并確保我將來會知道所有需要的道具。
- 我絕對不能將這些道具中的任何一個設為可選,因為它們
不是可選的。 - 還嘗試將狀態型別設定為
NotificationValuesType | []但打字稿不斷大喊大叫 - 我了解了型別斷言并猜測它應該有幫助,但找不到在狀態上使用它的任何示例。我可以做類似的事情嗎
const [dropdownsState, setDropdownsState] = useState as <NotificationValuesType>([])???
感謝您一直閱讀到最后!=)
uj5u.com熱心網友回復:
我絕對不能將這些道具中的任何一個設為可選,因為它們不是可選的。
也許不是在您完成后,而是在您構建它的程序中,如果值需要為undefined,則型別需要反映這一點。因此,您很可能希望狀態變數具有可選屬性,然后您按照步驟填寫它,一旦您驗證了所有內容,您就可以將其分配給具有屬性型別的變數都是強制性的。
有一種稱為輔助型別Partial,它將接受一個型別并產生一個新的型別,該型別的屬性是可選的。
// Note: this type is just the individual object, not the array that you have
type Example = {
channel: string
for: NotificationUsageTypes
id: string
type: NotificationTypes
workspace: string
}
const [dropdownsState, setDropdownsState] = useState<Partial<Example>[]>([])
// Later on, once you've verified that all the properties exist you can
// assert that it's done. I don't know exactly what your verification
// code will look like, but here's an example
if (dropdownsState.every(value => {
return value.channel && value.for && value.id && value.type && value.workspace
})) {
const finishedState = dropdownsState as Example[];
// do something with the finished state
}
編輯:正如評論中所指出的,如果您使用type guard,那么 typescript 可以縮小型別范圍并使您不必重新分配它:
if (dropdownsState.every((value): value is Example => {
return value.channel && value.for && value.id && value.type && value.workspace
})) {
// Inside this block, typescript knows that dropdownsState is an Example[]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392699.html
