为 Typescript 联合类型编写更具描述性的智能感知文档

Writing more descriptive intellisense docs for Typescript Union Types

给定以下代码,当我们调用 baz 函数时,预输入将显示 'a' 和 'b' 作为可能的值。

但是,如果我想为每个值提供额外的文档,我该怎么做?例如,如果需要这样的行为:

编辑:

我认为我应该提供更多有关我正在尝试做的事情以及原因的背景信息:

考虑以下示例:

const paintColor = {
  /** This color is good fo X */
  Waltz: "#d9e5d7",
  /** This color is good fo Y */
  "Indiana Clay": "#ed7c4b",
  /** This color is good fo Z */
  Odyssey: "#575b6a"
};

const locations = {
  /** There are no good school at this location*/
  City: "123 city center road",
  /** There are lots of parking at this location but it is very far*/
  West: "245 some other road"
};

interface HouseProp {
  color: keyof typeof paintColor; //"Waltz" | "Indiana Clay" | "Odyssey"
  location: keyof typeof locations; //"City" | "West"
}

const House = ({ color, location }: HouseProp) => {
  ...
};

其中 House 是一个根据颜色和位置道具渲染房屋的反应组件。

并且这个House组件在整个项目中无处不在。

在当前设置下,我可以像这样使用 House:

<House color="Indiana Clay" location="City" />

问题是,智能感知无法识别我作为代码的一部分编写的文档:

我想要的是:

P.S。我知道我可以将 paintColor 和位置变成枚举,并使用这样的东西:

import House, {HouseColor, HouseLocation} from './House';
<House color={HouseColor["Indiana Clay"]} location={HouseLocation.City} />

但是那个组件界面不如我最初的提议那么好。

你不能真正注释工会成员。但是,您可以以不同的方式表达联合 — 通过使用重载或选择使用枚举。

解决方案 #1:函数重载

/**
 * a is good fo X
 */
function baz(param: 'a'): number;
/**
 * b is an excellent choice for Y
 */
function baz(param: 'b'): number;
function baz(param: 'a' | 'b'): number {
  return 1;
}

Screenshot

解决方案 #2:作为接口重载

interface Baz {
  /**
   * a is good fo X
   */
  (param: 'a'): number;
  /**
   * b is an excellent choice for Y
   */
  (param: 'b'): number;
}

const baz: Baz = (param: 'a' | 'b') => {
  return 1;
}

Screenshot

解决方案 #3:改用枚举

enum Foo {
  /**
   * a is good fo X
   */
  A = 'a',
  /**
   * b is an excellent choice for Y
   */
  B = 'b',
}

function baz(param: Foo) {
  return 1;
}

Screenshot

我知道这不是您想要的,但这是您的次优选择。