Search code examples
typescriptdictionary

How to extend an interface but limit the keys to a specific list


In typescript, how can I extend an existing interface but limit the use to the same keys?

Existing interface:

interface First {
  key1: string;
  key2: string;
}

interface Second extends First {
  key1: number;
  key3: string <<< this must be prevented and generate error!
}

The example is intentionally reduced to understand the topic, obviously the application is for much more complex interfaces.

In all the tests I've done, when I extend an interface I can always add any kind of new key.


Solution

  • You can just override :

    type Override<T, U extends { [K in keyof T]?: any }> = {
      [K in keyof T]: T[K] extends U[K] ? T[K] : U[K]
    }
    
    interface First {
      key1: string;
      key2: string;
    }
    
    interface Second extends First {
      key1: number;
      key3: string
    }
    
    type Third = Override<First, {key1:number}>
    
    var myOverride:Third = {
      key1: 5,
      key2: 'six'
    }