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

TypeScript实现接口的类时如何简化constructor重复赋值的冗余语法

最简实现方案(TS 4.4+ 支持,完全类型安全)

不需要逐个声明属性、逐个赋值,直接通过映射类型一次性声明类属性,配合Object.assign批量赋值即可:

// 建议遵循TS规范,接口名使用大驼峰命名
interface MyInterface {
    prop1: string;
    prop2: string;
    prop3: number;
    prop4: boolean;
    // ... 其余属性
    prop30: string
}

class MyClass implements MyInterface {
    // 一次性声明类包含MyInterface的所有属性和对应类型,无需逐个书写
    declare [K in keyof MyInterface]: MyInterface[K];
    
    // 可以在此处正常声明类的额外自定义属性
    extraCustomProp: number = 100;

    constructor(data: MyInterface) {
        // 批量赋值,无需逐个写赋值语句
        Object.assign(this, data);
    }

    // 正常添加类方法即可,属性访问有完整类型提示
    customMethod() {
        console.log(this.prop1.toUpperCase());
        console.log(this.prop3.toFixed(2));
    }
}

低版本TS兼容方案

如果使用的TS版本不支持类内映射类型声明,可以用索引签名的方式兼容,缺点是类型校验粒度稍粗:

class MyClass implements MyInterface {
    [key: string]: any;

    constructor(data: MyInterface) {
        Object.assign(this, data);
    }
}

补充说明

如果你的场景不需要封装类方法,只是需要生成符合MyInterface类型的对象,直接用工厂函数更轻量化,不需要定义类:

function createMyObj(data: MyInterface): MyInterface {
    return { ...data };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:15:03