![](/img/trans.png)
[英]What's the best way to use a type assertion with destructuring assignment?
[英]what's the best way to type a mock store?
我們的測試代碼在我們的測試中充斥着這樣的代碼......
const mockState = {
client: {
users: {
results: {
something: -91893.21,
},
},
},
};
顯然 mockState 是無類型的。 我不能將其鍵入為 RootState,因為該接口具有該測試不需要的大量屬性。
我查看了 Partial 和 DeepPartial 但它們並沒有真正幫助,因為任何 json 都會實現任何 DeepPartial,因為每個屬性都是可選的。 有沒有辦法輸入 json object 以便它的所有屬性都匹配特定類型,但並非所有屬性都是必需的。 令人困惑的問題。 我想將 mockState 輸入到 IWhatever 以便它不會編譯,除非 IWhatever 有一個名為 client 的屬性,它有一個名為 users 等的屬性。
如果您在執行變量定義object的同時進行賦值,那么新鮮度就會啟動,並且會阻止您添加任何其他屬性。
type RootState = {
client: {
a: {
something: number
},
b: {
something: number
}
},
server: {
a: {
something: number
},
b: {
something: number
}
}
}
// Reference DeepPartial
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends Array<infer U>
? Array<DeepPartial<U>>
: T[P] extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: DeepPartial<T[P]>
};
// Okay
const mockState: DeepPartial<RootState> = {
client: {
a: {
something: 123
}
}
}
// Not Okay
const mockStateBad: DeepPartial<RootState> = {
client: {
a: {
somethings: 123 // ERROR
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.