将接口的对象转换为其基本接口

时间:2019-04-15 04:23:26

标签: typescript

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。我想将personWithPhone转换为person,即personWithPhone.phone = undefined。我不想更改对象,但同时我不想单独设置每个属性。像下面这样

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

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

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

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

1 个答案:

答案 0 :(得分:0)

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

其中一个选项是object destructuring

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

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

这里phone的{​​{1}}属性进入personWithPhone变量,所有rest都进入phone