对象解构和转换

时间:2019-09-13 19:40:15

标签: typescript

我有两个界面:

export interface Foo {
  __typename: "Foo";
  id: string;
  name: string | null;
  otherThing: string | null;
}

export interface Bar {
  __typename: "Bar";
  id: string;
  name: string | null;
}

我想将Foo类型的对象转换为条形。我可以内联对象分解吗?

2 个答案:

答案 0 :(得分:3)

由TypeScript声明的接口不是“真实的”,这意味着它们不是碰巧实现它们的对象的固有属性。接口只是编译时的抽象,用于安全检查,代码分析和代码完成帮助。没有什么可以“转换”的。这些对象只是对象,您可以随时使用它们。

要说服TypeScript接受正在使用的对象,就好像它实现了它最初并未实现的特定接口一样,您可以将该对象投射为其他类型,但是不能像解构之类的任何东西否则需要创建新对象或复制数据。该对象保留其原始属性,而TypeScript编译器只是以不同的方式查看它。

哦,只是要确保您知道...

__typename: "Foo";

...没有将值“ Foo”分配给__typename,它只是告诉TypeScript“ Foo”是您在TypeScript代码中唯一可以分配给__typename的值,除非您使用强制转换或其他技巧使TypeScript忽略接口所允许的内容。

答案 1 :(得分:2)

您使用的是品牌类型,所以并不是真的...如果__typename不太严格,则可以将Foo键入Bar中(但反之则不行)。但是,这违背了品牌类型的目的。即

const x: Foo = { __typename: "Bar", id: '1', name: 'x', otherThing: 'otherThing' }

将是有效的。

解构有什么问题?您仍然可以“内联”进行操作。

const foo: Foo = { __typename: "Foo", id: '1', name: 'x', otherThing: 'otherThing' }
const bar: Bar = { __typename: "Bar", id: '1', name: 'y' }

const fooToBar: Bar = { ...foo, __typename: "Bar" }
const barToFoo: Foo = { ...bar, otherThing: 'otherThing', __typename: "Foo" }
再次

请记住,bar-> foo缺少otherThing

编辑:这更像是“喷溅”而不是破坏性的例子,但是这个想法仍然存在。