Home > Software design >  How to ensure that string is one of the keys of an object in a prop that accepts string?
How to ensure that string is one of the keys of an object in a prop that accepts string?

Time:08-31

Here is the streamlined prop definition of a component from a package (I don't control).

interface InputProps {
  name: string,
  value?: string
}

Here is the streamlined type definition of my form.

interface IForm {
  name: string,
  email: string,
}

type KForm = keyof IForm

Here is my code where I deliberately put a wrong string, but it does not show error.

...
 <Input name={'emailx' as KForm} />
...

I had the following solutions that check the type, but I don't know if any of it is a good practice.

  1. Self-executing function
...
 <Input name={((k: KForm)=>k)('email')} />
...
  1. Same as above, but separate it elsewhere.

const getFieldName = (k: KForm) => k;

...
 <Input name={getFieldName('email')} />
...
  1. Declare separate variable.
const emailField: KForm = 'email';
...
 <Input name={emailField} />
...
  1. A wrapper component.
interface WrapperInputProp extends InputProp {
  name: KForm
}
...
<WrapperInput name={'email'} />

CodePudding user response:

Option 4 is the best in my opinion followed by option 3. Both of these provide static type checking at transpile time.

  • Related