0

I forget the term for the definition of the type { [type: string]: string}.

I had an example from another source of creating a type array { [type: string]: string} definition. I have used this a lot, and now need to change a sample to return differently based on parameters now be optional.

export function TextStringConstraintsFor(ColumnName: string, MinLength: number, MaxLength: number): { [type: string]: string } {
    return {
        ['isDefined']: 'should not be null or undefined',
        ['isString']: 'must be a string',
        ['maxLength']: 'must be shorter than ...',
        ['minLength']: 'must be longer than ...',
    }
}

If I change the MaxLength to be optional, I do not want the 'maxLength' entry in the return. Can this be one in line, or with a variable defined for the type?

I know I can do:

if (MaxLength === undefined) {
    return {
        ['isDefined']: 'should not be null or undefined',
        ['isString']: 'must be a string',
        ['maxLength']: 'must be shorter than ...',
        ['minLength']: 'must be longer than ...',
    }
} else {
    return {
        ['isDefined']: 'should not be null or undefined',
        ['isString']: 'must be a string',
        ['minLength']: 'must be longer than ...',
    }
}

I was wondering if it can be done using a variable or inline evaluation:

const Constraints: {[type: string]: string} =
    ['isDefined']: `${ColumnName} should not be null or undefined`,
    ['isString']: `${ColumnName} must be a string`,
}
if (MaxLength > 0) {
    Constraints.??? {
        ['maxLength']: `${ColumnName} must be shorter than or equal to ${MaxLength.toString()} characters`,
    }
}

or something along that line. Inline in the return would be valid for my use case as well.

Steven Scott
  • 10,234
  • 9
  • 69
  • 117

0 Answers0