打字稿通用密钥如何?

时间:2019-03-07 14:58:25

标签: javascript typescript

我想让

interface IBar {
  foo: IFoo;
  foo2: IFoo2;
}

转换类型,因为IBar是动态的T

interface IBar {
  foo: any;
  foo2: any;
}

我的代码

// a.ts
interface IBar {
   foo: IFoo;
   foo2: IFoo2;
}
// error is missing the following properties from type 
usePage<IBar>({ foo: ..., foo2: ... })

// b.ts
const usePage = <T extends {}>(params: T) => {
  ...
}

谢谢,我找到了解决方法:

interface PageRenderProps<T extends any, K extends any> {
  blocks: {
    [P in keyof T]: any;
  };
  pageData: {
    [Q in keyof K]: any
  };
}

1 个答案:

答案 0 :(得分:3)

像这样吗?

interface IBar<T, A> {
  foo: T;
  foo2: A;
}