logoalt Hacker News

g947olast Sunday at 11:18 PM3 repliesview on HN

Last time I checked, there isn't a way to extend types (https://www.typescriptlang.org/docs/handbook/2/objects.html#...) that works exactly like in TypeScript.


Replies

culilast Sunday at 11:31 PM

JSDoc actually has the @extends tag

  /**
   * @typedef {object} Dog @extends Animal
   * @property {string} childProp
   */
But I don't really use that feature in TypeScript. Instead I rely on `&`. This works in exactly the same way in JSDoc.

Also if you're curious about the equivalent of `extends` in generic slots, here's an example I have from a different project

  /**
   * @template {Record<string, unknown>} [T=Record<string, unknown>]
   * @typedef {{
   *   children?: NewickNode<T>[];
   *   name?: string;
   *   length?: number;
   *   data?: T;
   * }} NewickNode
   */
The generic slot here, T, is "extended" by Record<string, unknown>. The equivalent in TypeScript would look like

  type NewickNode<T extends Record<string, unknown> = Record<string, unknown>> = {
    children?: NewickNode<T>[];
    name?: string;
    length?: number;
    data?: T;
  };
show 2 replies
auxiliarymooselast Sunday at 11:25 PM

You can use `&` operator to combine types. Works for adding fields, making branded types, etc.

show 1 reply