How to override TSDoc/JSDoc from props that are common to multiple prop type definitions?
When working with TypeScript, you might come across a situation where you have multiple prop type definitions that share common props. In such cases, you may want to override the TSDoc/JSDoc comments for those common props without duplicating the comments in each prop type definition. In this blog post, we will explore different solutions to achieve this.
Solution 1: Using intersection types
One way to override TSDoc/JSDoc comments for common props is by using intersection types. Intersection types allow you to combine multiple types into one. Here’s an example:
type CommonProps = {
/**
* Common prop 1
*/
prop1: string;
};
type PropType1 = CommonProps & {
/**
* Prop type 1 specific prop
*/
prop2: number;
};
type PropType2 = CommonProps & {
/**
* Prop type 2 specific prop
*/
prop3: boolean;
};
In the above example, we define a type CommonProps
which contains the common props along with their TSDoc/JSDoc comments. Then, we create two prop type definitions PropType1
and PropType2
by intersecting CommonProps
with the specific props for each type. This way, the TSDoc/JSDoc comments for the common props are inherited without duplication.
Solution 2: Using utility types
Another approach is to use utility types provided by TypeScript. Specifically, we can use the Omit
utility type to exclude the common props from the specific prop type definitions. Here’s an example:
type CommonProps = {
/**
* Common prop 1
*/
prop1: string;
};
type PropType1 = Omit & {
/**
* Prop type 1 specific prop
*/
prop2: number;
};
type PropType2 = Omit & {
/**
* Prop type 2 specific prop
*/
prop3: boolean;
};
In this solution, we use the Omit
utility type to exclude the common prop prop1
from the specific prop type definitions. This way, the TSDoc/JSDoc comments for the common prop are not duplicated.
Solution 3: Using an intermediate type
Alternatively, we can define an intermediate type that includes the common props along with their TSDoc/JSDoc comments and then use that type in the specific prop type definitions. Here’s an example:
type CommonProps = {
/**
* Common prop 1
*/
prop1: string;
};
type PropType1 = {
/**
* Prop type 1 specific prop
*/
prop2: number;
} & CommonProps;
type PropType2 = {
/**
* Prop type 2 specific prop
*/
prop3: boolean;
} & CommonProps;
In this solution, we define the CommonProps
type with the common props and their TSDoc/JSDoc comments. Then, we include this type using the intersection operator (&
) in the specific prop type definitions. This way, the TSDoc/JSDoc comments for the common props are inherited without duplication.
These are three different solutions to override TSDoc/JSDoc comments for props that are common to multiple prop type definitions in TypeScript. Choose the solution that best fits your use case and enjoy cleaner and more maintainable code!
Leave a Reply