[英]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.