[英]Is it passible to enforce a TypeScript interface to contain specific keys?
假设我有一个从类似这样的东西推断出来的类型:
const foo = { a: 1, b: 2 };
type FooType = typeof foo;
是否可以使用该类型的密钥来强制执行接口中的密钥? 例如,我希望它通过 TypeScript 编译器:
interface OkInterface {
a: string; // the type should not matter
b: string;
}
但这不应该:
interface NotOkInterface {
a: string;
c: string; // b is missing and an extra key 'c' is present
}
我在想这样的事情:
interface FooKeys implements {[key: keyof FooType]: any} {
...
}
类型更灵活,是处理用例的唯一方法:
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
}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.