2

How to ensure that provided "inner interface" in interface ExampleActions like for example testAction one, have to strictly match Action interface? No avocado-like properties allowed.

interface Action {
    resultType?: any;
    data?: any;
}

type Actions = Record<string, Action>;

interface ExampleActions extends Actions {
    testAction: {
        resultType: number;
        data: string;
        avocado: boolean; //Here should be error? Action interface hasn't property avocado
    }

    //Here is error as expected:
    //Property 'invalidAction' of type 'string' is not assignable to 'string' index type 'Action'.(2411)
    invalidAction: string;
}
Sonaht
  • 85
  • 6
  • 1
    You're _extending_ `Actions`, why wouldn't you be able to add things to it? If you have an `ExampleActions`'s `testAction` then that _is_ usable by anything that expects an `Action` (and the consumer wouldn't have access to the extra props anyway). – jonrsharpe Mar 07 '23 at 18:30
  • @jonrsharpe Yes, but is it possible to restrict it? – Sonaht Mar 07 '23 at 18:32
  • Why do you think you want to? What's the context here? – jonrsharpe Mar 07 '23 at 18:32
  • @jonrsharpe the context is that it would help other persons to don't make a mistakes, like typing `datas` instead of `data`. Also (less important) refactoring code in IDE is missing the connection when I'd like to change name of lets say `resultType` property. – Sonaht Mar 07 '23 at 18:34
  • That mistake _would_ be caught, because then `data` would be missing. – jonrsharpe Mar 07 '23 at 18:34
  • @jonrsharpe won't be caught because isn't required, can be any, undefined too – Sonaht Mar 07 '23 at 18:35
  • Then don't write overbroad types to start with, what use is defining the property if that doesn't give you any information about what will be in it? Point remains: they're _still valid `Action`s_, so the compiler _shouldn't_ reject them. – jonrsharpe Mar 07 '23 at 18:36
  • The use is to restrict to only these two names, which keeps coding safe and minimize mistakes. – Sonaht Mar 07 '23 at 18:39
  • @njzk2 unfortunatelly it wont help, because it utilizes method for restricting it as function argument, it doesn't apply to inner interface pattern. Besides it would be very messy solution. – Sonaht Mar 07 '23 at 18:51
  • 2
    It would, but the point is mostly to show that TS does not include a simple mechanism for restricting extra properties on a declared type – njzk2 Mar 07 '23 at 18:53

0 Answers0