'Typescript asserting types if they have one property true or false [duplicate]
I have the following function:
type Option = {
map?: {
lat: number,
lng: number
}
location?: boolean
}
const foo = (option: Option) => {
if (option.map) {
return {
lat: option.map.lat,
lng: option.map.lng,
}
}
if (option.location) {
return 'location'
}
}
- if I call it with
foo()
, Typescript complains there should be 1 argument (as expected) - if I call it with
foo({})
, Typescript does not complain - I can call it with
foo({ map: {lat: 1, lng: 1 }})
orfoo({ location: true })
with no problems.
How can I tell typescript that the object HAS to have one of or map
or location
? So that foo({})
is not accepted?
The following question: is there a way to tell Typescript they are exclusive properties? Eg: if there's a map
, there can't be a location
and vice-versa?
Thanks a lot.
(I'm truly sorry if this is a duplicate. I can't even begin to think how to search this or what terms to use.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|