Say I have a function in which I want to only allow a property if another property is present.
I tried to do it like this, but it returns with error Property 'c' does not exist on type 'A'.
type A = {
a?: string;
} & ({ b: string; c?: string } | { b?: string });
const sad = (props: A) => {
const { a, b } = props;
const { c } = props; // Property 'c' does not exist on type 'A'.
return { a, b };
};
Any solutions to this?
The only way i know is User defined Type Guard and i like to combine it with Union Types
interface CommonProps {
a?: string
b?: string
}
interface SimpleProps extends CommonProps {
kind: "simple"
}
interface ComplexProps extends CommonProps {
kind: "complex"
c?: string
}
type Props = SimpleProps | ComplexProps
function isComplex(arg: Props): arg is ComplexProps {
return arg && arg.kind === 'complex'
}
const sad = (props: Props): any => {
if (isComplex(props)) {
const {a, b, c} = props
// do something
// return something
}
const { a, b } = props
// do something
// return something
}
In a nutshell, i create an interface for each possible combinations of properties. Then i Union them under the Props
types, and in my function i use the user defined guards
to access the properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With