gaurav5430
gaurav5430

Reputation: 13902

Typescript: reuse type descriptions / comments

I have 2 functions which have some common arguments:

func1(a, b, c)

func2(a, c, d)

I want to define the types for the functions in a way that I can reuse the definition for the common types along with the comments.

This is how I am currently typing common types and reusing the types:

type A = string;
type B = Array<string>;
type C = { p: string };
type D = number;

and using these as such in the function definitions:

type Func1 = (a: A, b: B, c: C) => void;
type Func2 = (a: A, c: C, d: D) => void;

this lets me reuse the type definition for A and C across the function type definitions, but when I add comments to describe the types, the comments don't show up in the IDE intellisense.

/** user id */
type A = string;
/** document ids */
type B = Array<string>;
/** user details */
type C = { p: string };
/** user age */
type D = number;

It seems I need to re-add the comments in the function type definitions. Is there an easy way to define types so that the comments get reused as well?

One way I can think of is to define smaller interfaces and add comments on interface properties, and while defining the function type extend those interfaces. This might look ok for sharing common types in 2 functions, but does not seem scalable where a combination of different types can be shared across functions.

Playground

Upvotes: 1

Views: 364

Answers (1)

RG3
RG3

Reputation: 79

I think your issue is more related to the IDE or Editor you are using than anything in actual code (at least from what I can tell with the given information).

I know I have had issues in the past with Visual Studio Code when adding several typings to my Angular/TypeScript projects outside of the Angular cli or multiple types into one file. The work around I've always done is to restart VS Code so the changes take place.

Something else that may help is looking into modules or plugins for the IDE that add the comments for you automatically when you import the type into your files. I am not super familiar with modules that would do this but I imagine that there are several solutions out there to help with this behavior.

Upvotes: 2

Related Questions