扩展类并为现有属性赋予不同的值

前端开发 2026-07-11

我在尝试扩展一个类并为已经在父类中定义的属性赋予不同的值。新的取值来自允许的取值:

/** @typedef {'a'|'b'|'c'} Letter */ 

class X {  
    constructor() {  
        /** @type {Letter} */  
        this.property = 'a';  
    }  
}  

class Y extends X {  
    constructor() {  
        super();  

        this.property = 'b';  
    }  
}

我得到了一个错误:

Class 'Y' incorrectly extends base class 'X'.
  Types of property 'property' are incompatible.
    Type 'string' is not assignable to type 'Letter'.

我到底哪里没搞懂?难道我必须在子类中重新定义 property 类型吗?

下面是 TypeScript playground 中的上述代码。

编辑:我已经从该类中提取了类型。

解决方案

关于 其他回答 的问题在于类型注解 /** @type {'a'|'b'|'c'} */ 不能被复用。你必须重复它,这违反了S.P.O.T.原则(Single Point of Truth,单一信息源原则)。这真的不好。

为了让类型注解按你预期的方式工作,你可以显式地声明 typedef 来重复使用它:

/**
 * @typedef { 'a' | 'b' | 'c' } ValidLetters
 */

class X {
    constructor() {
        /** @type {ValidLetters} */
        this.property = 'a';
    }
}

class Y extends X {
    constructor() {
        super();
        /** @type {ValidLetters} */
        this.property = 'b';
        // this.property = 'e'; // will not pass validation
    }
}

// test:

const x = new X();
console.log(x.property); // a

const y = new Y();
console.log(y.property); // c

请注意,JSDoc的类型检查仅用于验证。如果验证失败(例如你取消注释 this.property = 'e'; 的情形),脚本将会成功执行。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章