Let's say we have the following Typescript interface
:
interface Sample {
key1: boolean;
key2?: string;
key3?: number;
};
In this case, key1
is always required, key2
is always optional, while key3 should exist if key1
is true
and should not exist if key1
is false
. In another word, a key's occurrence depends on another key's value. How can we achieve this in Typescript?
In TypeScript, you can specify that some or all properties of an object are optional. To do so, just add a question mark (?) after the property name.
If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional. Copied!
Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.
The TypeScript Omit utility type Like the Pick type, the Omit can be used to modify an existing interface or type. However, this one works the other way around. It will remove the fields you defined. We want to remove the id field from our user object when we want to create a user.
The most straightforward way to represent this is with a type alias instead of an interface:
type Sample = {
key1: true,
key2?: string,
key3: number
} | {
key1: false,
key2?: string,
key3?: never
}
In this case the type alias is the union of two types you're describing. So a Sample
should be either the first constituent (where key1
is true and key3
is required) or the second constituent (where key1
is false and key3
is absent).
Type aliases are similar to interfaces but they are not completely interchangeable. If using a type alias leads to some kind of error, please add more detail about your use case in the question.
Hope that helps. Good luck!
I also really like the way Ben Ilegbodu (https://www.benmvp.com/blog/conditional-react-props-typescript/) does it:
Give these three different cases in JSX:
<Text>not truncated</Text>
<Text truncate>truncated</Text>
<Text truncate showExpand>truncated w/ expand option</Text>
... Here is the corresponding TypeScript definition to make the showExpanded
property required when the truncate
prop is present:
interface CommonProps {
children: React.ReactNode
// ...other props that always exist
}
type TruncateProps =
| { truncate?: false; showExpanded?: never }
| { truncate: true; showExpanded?: boolean }
type Props = CommonProps & TruncateProps
const Text = ({ children, showExpanded, truncate }: Props) => {
// Both truncate & showExpanded will be of
// the type `boolean | undefined`
}```
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