You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在带键重映射的映射类型中继承属性注解?

如何在TypeScript键重映射类型中继承原属性的JSDoc注解

默认情况下,你当前的Prefix映射类型只会复制原属性的类型,不会自动继承原属性的JSDoc注解。但可以通过以下方式实现需求:

方法1:继承原属性注解

使用/** @inheritDoc */标签显式引用原属性的JSDoc,修改映射类型如下:

type Prefix<Type, str extends string> = {
    [Property in keyof Type as `${str}${Capitalize<string & Property>}`]: 
    /** @inheritDoc Type[Property] */
    Type[Property]
};

interface Person {
    /** This is the name. */
    name: string;

    /** This is the age. */
    age: number;

    /** This is the location. */
    location: string;
}

interface A extends Prefix<Person, 'alpha'>, Prefix<Person, 'beta'> {};

此时在VS Code等支持TypeScript的编辑器中悬停A.alphaName,会显示:(property) A.alphaName: string. This is the name.,完全符合你的需求。

方法2:可选覆盖注解

如果需要在特定场景下覆盖原注解,可以给映射类型添加一个可选的覆盖参数:

type Prefix<Type, str extends string, Overrides extends Partial<Record<keyof Type, string>> = {}> = {
    [Property in keyof Type as `${str}${Capitalize<string & Property>}`]: 
    Overrides[Property] extends string 
        ? /** ${Overrides[Property]} */ Type[Property]
        : /** @inheritDoc Type[Property] */ Type[Property]
};

interface Person {
    /** This is the name. */
    name: string;

    /** This is the age. */
    age: number;

    /** This is the location. */
    location: string;
}

// 仅覆盖name的注解,其他属性保留原注解
interface A extends Prefix<Person, 'alpha', { name: 'This is the alpha-specific name.' }>, Prefix<Person, 'beta'> {};

这种写法下,A.alphaName会显示自定义的注解,而alphaAge、alphaLocation依然保留原Person中的注解。

注意事项

  • 该功能依赖编辑器对TypeScript JSDoc的完整支持(如VS Code)
  • 需要确保TypeScript版本在4.7及以上,@inheritDoc在映射类型中的引用支持是该版本后完善的

内容的提问来源于stack exchange,提问作者Nono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:20:16