TypeScript: remove index signature using mapped types

前端 未结 3 1012
失恋的感觉
失恋的感觉 2020-12-03 10:41

Given an interface (from an existing .d.ts file that can\'t be changed):

interface Foo {
  [key: string]: any;
  bar(): void;
}

Is there a

3条回答
  •  抹茶落季
    2020-12-03 11:37

    There is not a really generic way for it, but if you know which properties you need, then you can use Pick:

    interface Foo {
      [key: string]: any;
      bar(): void;
    }
    
    type FooWithOnlyBar = Pick;
    
    const abc: FooWithOnlyBar = { bar: () => { } }
    
    abc.notexisting = 5; // error
    

提交回复
热议问题