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

如何在TypeScript中克隆Interface1以创建等价的Interface2?

TypeScript中克隆接口的方法

问题背景

我定义了如下接口:

interface Interface1 {
    property1: string;
    property2: string;
}

需要创建一个和Interface1完全一致的Interface2,虽然可以直接用Interface1替代,但想知道有没有办法克隆Interface1得到Interface2。类型别名可以直接通过type T2 = T1的方式克隆,但尝试用interface Interface2 extends Interface1时,ESLint抛出错误:Parsing error: '{' expected,想了解正确的克隆方法。

解决方案

有三种常用方式可以实现接口的克隆:

  1. 使用类型别名直接赋值
    这是最简洁的方式,和类型别名的克隆逻辑一致:
type Interface2 = Interface1;

这样Interface2就和Interface1完全等价,所有使用Interface1的地方都可以替换成Interface2。

  1. 修正extends语法的接口继承
    你之前的代码报错是因为接口继承时必须带上大括号(哪怕里面没有内容),正确写法如下:
interface Interface2 extends Interface1 {}

这种方式会创建一个独立的接口Interface2,它完全继承Interface1的所有属性,后续还可以在大括号里添加新的属性扩展接口。

  1. 使用Pick工具类型复制所有属性
    如果需要显式复制原接口的所有属性,可以用Pick工具类型:
type Interface2 = Pick<Interface1, keyof Interface1>;

这种方式会遍历Interface1的所有键并复制对应的属性定义,适合需要精确控制复制范围的场景,完全克隆的话就选择所有键。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:45:43