考虑以下代码,请注意someField的文档
interface Test {
/**
* Some description.
* lorum ipsum.
* foo bar.
*/
someField: string;
}
function withGeneric<T extends Test>(arg: T) {
return arg;
}
function withoutGeneric(arg: Test) {
return arg;
}
withGeneric({
someField: ""
});
withoutGeneric({
someField: ""
});当我将鼠标悬停在withoutGeneric调用中的someField上时,VSCode很好地向我显示了文档:

但是,当将鼠标悬停在withGeneric调用中的someField上时,不会显示文档:

有没有办法让tsdoc文档也能使用泛型参数?
发布于 2021-10-15 16:47:26
请考虑,在创建内联对象时,它的类型不是Test
const config = {
someField: ""
};
根据定义,您的withoutGeneric函数接受Test-typed参数,因此TypeScript可以推断属性类型。但是,如果您的函数是泛型的,但您没有显式设置泛型类型,那么TypeScript将从内联对象的类型推断泛型类型,这就是您在上面看到的默认推断类型。
您可以在intellisense中看到以下内容:

TypeScript将泛型类型推断为{ someField: string; }。这满足了Test接口的要求,但是该值是它自己推断的默认类型,而不是Test。
考虑以下示例:
interface Foobar {
/**
* Unrelated doc string
*/
someField: string;
}
const config:Foobar = {
someField: ""
}您将获得以下智能感知:

请注意,Foobar类型满足withGeneric函数的要求,因为它具有所需的属性,并且这些属性的类型正确。但是,与someField关联的文档字符串将是Unrelated doc string,因为这是config变量的类型。
如果您显式设置了函数的泛型类型,那么它的行为将与您预期的一样。
withGeneric<Test>({
someField: ""
});产生以下结果:

如果您显式地将类型设置为Foobar,那么您将获得Foobar的文档字符串:
withGeneric<Foobar>({
someField: ""
});收益率:

发布于 2021-10-18 08:00:55
我找到了一个适合我的答案。添加具有extended from类型的联合:
/**
* withGeneric sample
* @typeParam T - must be a Test
* @param arg
* @returns
*/
function withGeneric<T extends Test>(arg: T & Test) {
return arg;
}现在,VSCode确实显示了文档:

这感觉像是一场恶作剧,但我看不出它有什么缺点?
https://stackoverflow.com/questions/69587324
复制相似问题