2

I am writing my own custom form validators for angular with the following template.

static customFunction(param: number, param2: string): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    return { customError: {param, param2} };
  };
}

Instead of key:string I want to only allow a range of items from a defined enum.

export enum FormErrorEnum {
  unknown = 'unknown',
  customError = 'customError',
}

export type FormError = keyof typeof FormErrorEnum;

If I try to use either [key: FormError]: any or [key in FormError]:any I will get one of two errors.

[key: FormError]: any results in a TS1337. [key in FormError]:any results in the return (customError: {param,param2} being refused as it does not include all entires in the enum.


I have already looked in this thread. TS version is 3.8 - upgrading is an option.

Questioning
  • 1,903
  • 1
  • 29
  • 50

1 Answers1

3

You can use literal types instead of enums.

export type FormError  = 'unknown' | 'customError';

const error1: FormError = 'unknown'; // ok
const error2: FormError = 'illegal'; // error

The return type in your customFunction should be:

type ErrorResult = {
    [P in FormError]?: any;
};

If you allow exactly one property of FormError:

type ErrorResult = {
    [P in FormError]: { [K in P]: any };
}[FormError];

The idea behind this is: Create the required type for each key: { [K in P]: any }. Put them in a map: { [P in FormError]: {...} }. Get the values of the map: [FormError]

Mihályi Zoltán
  • 822
  • 6
  • 11