I have proptypes shown below
interface Props {
resource: string;
create?: boolean;
route?: string;
}
As can be seen above, create and route are optional props. However, I would like to implement the types such that if create prop is present then route must now be required. Anyone have any ideas how to do this?
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 exclude a property from a type, e.g. type WithoutCountry = Omit<Person, 'country'> . The Omit utility type constructs a new type by removing the specified keys from the existing type. Copied!
TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.
To pick a specific set of properties from an existing TypeScript type, and make them optional, you can do any of the following: Create a Custom Utility Type.
We can use this to transform a type with a mix of required and optional properties into a new type where all the properties are required but some of them may be undefined: This works by mapping over Required<T>, a version of our original type where all the optional properties have been replaced by required ones.
Create a Custom Utility Type. Since the Partial utility type in TypeScript does not allow selection of specific set of properties, you can simply combine it with the Pick utility type, which would have the following syntax: This would select " bar " and " qux " from " Foo ", and make them optional in the new type.
The optional parameters must appear after the required parameters in the parameter list. For example, if you make the b parameter optional, and c parameter required the TypeScript compiler will issue an error: error TS1016: A required parameter cannot follow an optional parameter. Use the parameter?: type syntax to make a parameter optional.
You should group these props and make that grouped prop optional as
interface RouteProps{
create: boolean;
route: string;
}
interface Props {
resource: string;
routeInfo?: RouteProps;
}
You can split it into a union of two types and use create
with a literal type:
type Props = {
resource: string;
create?: false;
route?: string
} | {
resource: string;
create: true;
route: string;
}
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