0
votes

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?

1
When you declare the index signature in the class, you need to use your TReturn type. You can get rid of the interface itself, it's just noise. - Aluan Haddad
Oh wow, good catch. If you post that as the answer I'm happy to accept it. For bonus points, I'd love a solution that avoids the index signature in the class altogether (that's what I'm trying to achieve with the interface, but it is admittedly noise if I also have to include the index signature). - RocketMan

1 Answers

0
votes

Just in case anyone runs into a similar need, I ended up using Record instead of my interface:

class MyMessages implements Record<keyof MyMessages, TReturn>  {

  a: string;
  b: (sVal?: string) => string;
  c: number; // error here, good!

}

Record docs: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype