TypeScript: remove index signature using mapped types

前端 未结 3 1020
失恋的感觉
失恋的感觉 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:28

    There is a way, requiring TypeScript 2.8's Conditional Types.

    It is based on the fact that 'a' extends string but string doesn't extends 'a'

    interface Foo {
      [key: string]: any;
      bar(): void;
    }
    
    type KnownKeys = {
      [K in keyof T]: string extends K ? never : number extends K ? never : K
    } extends { [_ in keyof T]: infer U } ? U : never;
    
    
    type FooWithOnlyBar = Pick>;
    

    You can make a generic out of that:

    // Generic !!!
    type RequiredOnly> = Pick>;
    
    type FooWithOnlyBar = RequiredOnly;
    

    For an explanation of why exactly KnownKeys works, see the following answer:

    https://stackoverflow.com/a/51955852/2115619

提交回复
热议问题