gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:22:59 25 4
gpt4 key购买 nike

给定以下代码,当我们调用 baz函数,预输入将显示 'a' 和 'b' 作为可能的值。
enter image description here
但是,如果我想为这些值中的每一个提供额外的文档,我该怎么做?例如,如果这样的行为是期望的行为:
enter image description here
编辑:
我认为我应该提供更多关于我正在尝试做的事情以及原因的背景信息:
考虑以下示例:

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 是一个 react 组件,它根据颜色和位置 Prop 渲染房子。
这个 House 组件在整个项目中随处可见。
使用当前设置,我可以像这样使用 House:
<House color="Indiana Clay" location="City" />
问题是,智能感知无法识别我作为代码一部分编写的文档:
enter image description here
我想要的是这样的:
enter image description here
附言我知道我可以将 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)重载
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
我知道这不是您想要的,但这是您的第二好的选择。

关于typescript - 为 Typescript 联合类型编写更具描述性的智能感知文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63067208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com