Search code examples
typescripttypescript-genericsunion-types

Restricting an interface to specific keys from a union type


I've got a union type listing some allowed keys : type AllowedKeys = "a" | "b";

Somewhere else, I'm declaring an interface, and I want to restrict this interface to the allowed keys :

interface Interface {
  a: Something; // This is fine
  c: SomethingElse; // I want this to throw an error
}

How could I write this to enforce that the interface respects the allowed keys ?


Solution

  • You cannot do that with interface, because

    This is because interfaces in TypeScript are open ended. This is a vital tenet of TypeScript that it allows you to mimic the extensibility of JavaScript using interfaces.

    basically you can always add new properties to an interface.

    Instead, you can try

    type AllowedTypes =  {
        "a" : string;
        "b": number ;
    }
    
    type AllowedKeys = keyof AllowedTypes;