Is it possible to restrict a typescript class to only contain members (attributes and functions) that return strings?
I've tried defining an interface:
export interface IMessages {
[index: string]: TReturn;
}
type sfunc = (sVal?: string) => string;
type TReturn = string | sfunc;
And then implementing it in a class:
class MyMessages implements IMessages {
[index: string]: string; // silly, see - https://github.com/Microsoft/TypeScript/issues/15300
a: string;
b: (sVal?: string) => string;
}
but typescript says that "Property 'b' of type '(sVal?: string | undefined) => string' is not assignable to string index type 'string'."
I get the feeling that I'm missing some kind of symbol definition in the interface that allows functions to be defined. At the end of the day, I really just want to enforce that all properties and functions defined in the class must return strings.
EDIT: after a comment revealed a mismatch in the index signatures, I'd like to bring up a relevant question - is there any way to avoid the index signature in the implementing class altogether?
TReturntype. You can get rid of the interface itself, it's just noise. - Aluan Haddad