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.
- Self-executing function
...
<Input name={((k: KForm)=>k)('email')} />
...
- Same as above, but separate it elsewhere.
const getFieldName = (k: KForm) => k;
...
<Input name={getFieldName('email')} />
...
- Declare separate variable.
const emailField: KForm = 'email';
...
<Input name={emailField} />
...
- 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.