首页 > 解决方案 > 将接口的对象转换为其基本接口

问题描述

interface IPerson {
    firstName: string;
    lastName:  string;
}

interface IPersonWithPhone extends IPerson {
    phone: string;
}

const personWithPhone: IPersonWithPhone = {
    firstName: "Foo",
    lastName: "Boo",
    phone: "+1 780-123-4567"
}

可以说IPersonWithPhone延伸IPerson。我想转换personWithPhoneperson, 意思personWithPhone.phone = undefined。我不想改变对象,同时我不想单独设置每个属性。像下面这样的东西,

// Not like this
const person: IPerson = {
    firstName: personWithPhone.firstName,
    lastName: personWithPhone.lastName
}

我正在寻找类似于 spread 的东西,它可以删除一个属性并可以转换为基本接口。

// example of spread
cont person: IPerson = {
    firstName: "Foo",
    lastName: "Boo",
}

const personWithPhone: IPersonWithPhone = {...person, phone: "+1 780-123-4567"};

标签: typescript

解决方案


类型信息在运行时不存在,所以这里没有神奇的解决方案。您需要指定要省略的属性。

选项之一是对象解构

const personWithPhone: IPersonWithPhone = {
    firstName: "Foo",
    lastName: "Boo",
    phone: "+1 780-123-4567"
}

const { phone, ...person } = personWithPhone;

这里phone的属性personWithPhone进入phone变量,其余的都进入person


推荐阅读