使用解构对象和散布运算符创建的对象类型

时间:2019-07-06 09:52:14

标签: typescript destructuring

我要键入我创建的foo

interface IFoo {
  b: number;
  c: number;
}
interface IBar {
  a: number;
  b: number;
  c: number;
}
const bar: IBar = { a: 1, b: 2, c:3 };
const { a, ...foo } = bar;

我在其他SO帖子上看到,我可以这样解决它:

const { a, ...foo }: { a: number, foo: IFoo } = bar;

但是随后出现以下Typescript错误:

  

TS2322:类型“ IBar”不可分配给类型“ {{a:number; foo:IFoo; }'。     类型“ IBar”中缺少属性“ foo”。

我想出了以下解决方案:

const typedFoo: IFoo = foo;

现在我可以将typedFoo用作类型化的对象而不是foo-但这是不雅的。

0 个答案:

没有答案
相关问题