This particular query has proven quite challenging for me to articulate, leading to difficulty in finding a definitive solution.
Below is the code snippet in question:
type myType = {
apple ?: any
banana ?: any
}
const sample = function(myObject : myType) {
if (typeof myObject.apple !== 'undefined' || typeof myObject.banana !== 'undefined') {
// Do something
} else {
// This will cause an error!
}
}
sample({ apple: true }) // This works fine
sample({ banana: 'hello world' }) // This works fine
sample({ apple: false, banana: 'foo bar' }) // This works fine
sample({}) // This does NOT work
sample({ banana: undefined }) // This does NOT work
sample({ taco: 'hello world' }) // This does NOT work
The goal here is to create a type that can identify instances where the input is not as expected.
My Query: How can I adjust myType
to generate an error when all of its keys are not set, yet still allow cases where at least one known key is set?
As an additional point: It seems plausible to utilize the approach below, but it appears somewhat clunky and may not be considered best practice. An alternative solution would be preferred given that my actual code contains numerous keys, making this method rather tedious.
type myType_1 = {
apple : any
banana ?: any
}
type myType_2 = {
apple ?: any
banana : any
}
type myType = myType_1 | myType_2