cubabit
cubabit

Reputation: 2700

Is it passible to enforce a TypeScript interface to contain specific keys?

Say I have a type that is inferred from something else like this:

const foo = { a: 1, b: 2 };
type FooType = typeof foo;

Is it possible to then use the keys in that type to enforce the keys in an interface? For example, I want this to pass in the TypeScript compiler:

interface OkInterface {
  a: string; // the type should not matter
  b: string;
}

But this should not:

interface NotOkInterface {
  a: string;
  c: string; // b is missing and an extra key 'c' is present
}

I am thinking of something like:

interface FooKeys implements {[key: keyof FooType]: any} {
  ...
}

Upvotes: 0

Views: 40

Answers (1)

Simon Bruneaud
Simon Bruneaud

Reputation: 2557

Types are more flexible and the only way to handle your use case:

const foo = { a: 1, b: 2 }
type FooType = typeof foo

type EnforceFooInterface<T extends Record<keyof FooType, any>> = T

type OkInterface = EnforceFooInterface<{
  a: string // the type should not matter
  b: string
}>

type NotOkInterface = EnforceFooInterface<{
  a: string
  c: string // b is missing and an extra key 'c' is present
}>

Upvotes: 1

Related Questions