class rules implements Record<keyof rules, ()=>void> {
test() {
}
}
When using just [key:string]: testFn
, it suggests that every possible string key will correspond to a function. However, your class is limited to a specific number of keys.
You can reference the keys of your own class in implemented interfaces by using
Record<keyof OWN_CLASS, testFn>
, which provides the type constraint you need.
It's important to note that in typescript, a function that returns anything can be assigned to a function that returns void, so constraining the return type may not be straightforward:
class rules implements Record<keyof rules, ()=>void> {
test() {
return "not void" // This doesn't trigger an error
}
}
To properly constrain the return type to always be void, you can take a more unique approach:
type AllFuncs<Cls> = {
[K in keyof Cls]: Cls[K] extends () => infer R
? R extends void
? testFn // If the return type is void, no issue
: () => undefined // If the return type isn't void, it must be undefined
: testFn; // If it's not a function, set constraint to function for error
};
class rules implements AllFuncs<rules> {
test() {
return "now is error :)"
}
}