Reputation: 7005
I have this enum that I use for creating types:
export enum MyTypeEnum {
one = 'one',
two = 'two',
three = 'three',
four = 'four'
}
export type MyTypeKeyFunctionValue = { [key in MyTypeEnum ]?: Function };
export type MyTypeKeyStringValue = { [key in MyTypeEnum ]?: string };
I have a class that contains getters using those exact keys:
export class MyClass {
get one() { ... implementation ...}
get two() { ... implementation ...}
get three() { ... implementation ...}
get four() { ... implementation ...}
}
I want to know if is there a way to create a interface that when implemented force the class to have those getters.
I tried with
interface IClass{
[key in MyTypeEnum ] : Function
}
But it does not work. Is this possible?
Upvotes: 1
Views: 65
Reputation: 250006
Those getters are represented in the class public API as just properties, so an interface that would force the implementer to have those property getters, would be equivalent to:
interface MyTypeKeyGetters = {
readonly one: any;
readonly two: any;
readonly three: any;
readonly four: any;
}
You can build such a type based on an enum, and implement it directly:
export enum MyTypeEnum {
one = 'one',
two = 'two',
three = 'three',
four = 'four'
}
export type MyTypeKeyGetters = {
readonly [key in MyTypeEnum]: any
};
export class MyClass implements MyTypeKeyGetters{
get one() { return ""; }
get two() { return ""; }
get three() { return ""; }
get four() { return ""; } // error if we omit one.
}
Note There is no way to guarantee the fields will be implemented with getters, an implementing class could also use a field.
While it is not actually an interface, it can be implemented as one. The mapped type syntax is not supported directly in interfaces. If you want to have an interface and not a type alias, you can define an interface extending the mapped type:
type MyTypeKeyGetters = {
readonly [key in MyTypeEnum]: any
};
export interface MyTypeKeyGettersInterface extends MyTypeKeyGetters { }
Upvotes: 3