简体   繁体   中英

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} {
  ...
}

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
}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM